[英]Javascript form being triggered by JQuery after changing id
我有一个表单,一旦提交,就使用$('#search_form').submit(function(){# execute code here});
执行一些JQuery $('#search_form').submit(function(){# execute code here});
。 稍后在代码中,我使用$('#search_form').attr('id', 'tags_form');
更改表单$('#search_form').attr('id', 'tags_form');
。 然后,当触发该表单时,我有一个不同的代码块。 问题是,当我使用新ID提交表单时,它仍会触发旧的.submit()
。
更改元素的id
不会从其中删除现有的处理程序。 首先解除绑定:
$('#search_form').unbind('submit');
当然可以,因为当您在启动时使用新的id tags_form
绑定事件时,该事件并不存在。 因此,事件绑定在那里不起作用。
而是尝试使用事件委托或在更改ID后绑定事件,或者为element指定一个类名,然后将事件绑定到该类名而不是ID。
$(document).on('submit', '#tags_form, #search_form', function(){# execute code here});
要么:
$('.myFormClass').submit(processForm); //where the classname on form is myFormClass
要么:
假设您的活动是这样的:
$('#search_form').on('click', processForm); // or $('#search_form').click(processForm);
后来:
// some code...
$('#search_form').off('submit'); // unbind the handler or $('#search_form').unbind('click');
//In the Code block that changes the id
$('#tags_form').on('submit', processForm); // bind the handler to new element
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.