一个页面上会有0-10个表格。每个都将允许用户对该表单的内容进行投票。我如何利用 javascript 捕获那些不同表单的点击事件,并将内容返回到特定表单的范围内。如果我为表单动态生成 ID,我该如何在 JavaScript 中对此进行说明?
最佳答案
如果您使用 jQuery JavaScript 库,那么您可以一次性将相同的函数附加到所有表单,并在回调函数中返回对表单的引用。例如,如果您正在等待用户提交表单以发送 AJAX 请求,您可以这样做:
// `$('form')` selects all the forms on the page
// `.submit();` will call a function when the submit event is fired on all forms
$('form').submit(function() {
// Store a reference to this form
var $thisForm = $(this);
$.ajax({
...
success: function() {
// do something with the $thisForm variable which is still in scope.
}
});
});
关于javascript - 如何使用javascript捕获多个表单的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4629313/