我有一张表格; 我已经将提交按钮更改为只键入"按钮",这样我就可以在提交表单之前运行一些JavaScript:
这是我的表格:
<form action="/Cart" method="post">
<input type="hidden" name="name" value="12" />
<input type="button" class="addToCartButton" value="Add to Cart" />
</form>
Run Code Online (Sandbox Code Playgroud)
这是我的初始事件处理程序:
$(document).ready(function () {
$('.addToCartButton').click(function () {
//need to reference current form here
//need to reference the hidden input with name="Name" above
});
});
Run Code Online (Sandbox Code Playgroud)
我在同一页面上有许多这些表单,所以我需要相对引用该表单中的表单和其他一些输入.这样做的最佳方式是什么?我正在考虑为每个表单添加一些独特的前缀,然后在选择器中使用它,但这看起来非常hacky ...
Dav*_*mas 13
这应该工作:
$(document).ready(function () {
$('.addToCartButton').click(function () {
//need to reference current form here
$(this).closest('form');
//need to reference the hidden input with name="Name" above
$(this).closest('form').find('input[name="name"]');
});
});
Run Code Online (Sandbox Code Playgroud)
jQuery Closest() 将沿树向上移动并返回与选择器匹配的第一个元素:
$(this).closest("form");
Run Code Online (Sandbox Code Playgroud)