我的 php 页面中有多个表单, 我像这样在parentForm数组中添加了表单
parentForm.push($('.js-address-form form'));
问题是当我提交一个表单时,页面中存在的所有表单都会触发 onsubmit 事件,因此如果我有 2 个表单,则 ajax 请求将被调用 2 次。
jQuery.each(parentForm, function(i, val) {
$(document).on('submit',val, function(event) {
$.ajax({
type: method,
url: lpd_front_controller,
async: false,
data: {
ajax: true,
action: 'Add',
id_customer: lpd_id_customer,
customer_token: lpd_customer_token,
id_guest: lpd_id_guest,
guest_token: lpd_guest_token,
consent_section: consent_section[i]
},
error: function(err) {
console.log(err);
}
});
});
});
我喜欢当我提交表单时,表单 onsubmit 事件将被触发一次
您的问题是
.on
jquery 函数不接受 jquery 对象作为第二个参数,只接受另一个选择器:
.on( events [, selector ] [, data ], handler )
选择器
类型:字符串
一个选择器字符串,用于过滤触发事件的所选元素的后代。如果选择器为 null 或省略,则事件始终在到达所选元素时触发。
您可以在事件中使用原始选择器,例如:
$(document).on('submit', '.js-address-form form', function(event) {
或者直接在循环中添加事件 - 考虑到您如何基于现有项目创建循环,您不需要事件委托,因此:
jQuery.each(parentForm, function(i, val) {
$(val).on('submit', function(event) {