简体   繁体   English

更改ID后由JQuery触发Javascript表单

[英]Javascript form being triggered by JQuery after changing id

I have a form that, once submitted, executes some JQuery using $('#search_form').submit(function(){# execute code here}); 我有一个表单,一旦提交,就使用$('#search_form').submit(function(){# execute code here});执行一些JQuery $('#search_form').submit(function(){# execute code here}); . Later on in the code, I change the id of the form with $('#search_form').attr('id', 'tags_form'); 稍后在代码中,我使用$('#search_form').attr('id', 'tags_form');更改表单$('#search_form').attr('id', 'tags_form'); . Then, I have a different block of code when that form is triggered. 然后,当触发该表单时,我有一个不同的代码块。 The problem is that when I submit the form with the new id, it still triggers the old .submit() . 问题是,当我使用新ID提交表单时,它仍会触发旧的.submit()

Changing the id of an element doesn't remove existing handlers from it. 更改元素的id不会从其中删除现有的处理程序。 Unbind it first: 首先解除绑定:

$('#search_form').unbind('submit');

Yes of course because when you bound the event using new id tags_form at the start up it doesn't just exist. 当然可以,因为当您在启动时使用新的id tags_form绑定事件时,该事件并不存在。 So event binding is of no effect there. 因此,事件绑定在那里不起作用。

instead try using event delegation or bind the event after changing the id, or assign a classname for element and bind the event to the classname instead of the id. 而是尝试使用事件委托或在更改ID后绑定事件,或者为element指定一个类名,然后将事件绑定到该类名而不是ID。

$(document).on('submit', '#tags_form, #search_form', function(){# execute code here});

Or: 要么:

$('.myFormClass').submit(processForm); //where the classname on form is myFormClass

Or: 要么:

Say you event is like this: 假设您的活动是这样的:

$('#search_form').on('click', processForm); // or $('#search_form').click(processForm);

Later: 后来:

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM