Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
更改id后JQuery触发的Javascript表单_Javascript_Jquery_Forms - Fatal编程技术网

更改id后JQuery触发的Javascript表单

更改id后JQuery触发的Javascript表单,javascript,jquery,forms,Javascript,Jquery,Forms,我有一个表单,一旦提交,就会使用$('#search_form')执行一些JQuery。稍后在代码中,我用$('search_form')更改表单的id。attr('id','tags_form')。然后,当表单被触发时,我有一个不同的代码块。问题是,当我使用新id提交表单时,它仍然会触发旧的.submit()当然是,因为在启动时使用新id标记绑定事件时,表单并不存在。因此,事件绑定在那里没有效果 改为尝试使用事件委派或在更改id后绑定事件,或为元素分配一个类名,并将事件绑定到类名而不是id $

我有一个表单,一旦提交,就会使用
$('#search_form')执行一些JQuery。稍后在代码中,我用
$('search_form')更改表单的id。attr('id','tags_form')。然后,当表单被触发时,我有一个不同的代码块。问题是,当我使用新id提交表单时,它仍然会触发旧的
.submit()

当然是,因为在启动时使用新id
标记绑定事件时,表单并不存在。因此,事件绑定在那里没有效果

改为尝试使用事件委派或在更改id后绑定事件,或为元素分配一个类名,并将事件绑定到类名而不是id

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

或:

假设你的活动是这样的:

$('#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

当然可以,因为当您在启动时使用新id
tags\u form
绑定事件时,它不仅仅存在。因此,事件绑定在那里没有效果

改为尝试使用事件委派或在更改id后绑定事件,或为元素分配一个类名,并将事件绑定到类名而不是id

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

或:

假设你的活动是这样的:

$('#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

更改元素的
id
不会从中删除现有的处理程序。首先解除绑定:

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

更改元素的
id
不会从中删除现有的处理程序。首先解除绑定:

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

更改元素的属性或属性,甚至它的内容,都不会更改绑定到它的事件。更改元素的属性或属性,甚至它的内容,不会更改绑定到它的事件。此解决方案是否也会阻止旧函数触发?或者您可以像上面的回答那样解除旧事件的绑定。此解决方案是否也会阻止旧函数触发?或者您可以像上面的回答那样解除旧事件的绑定。