簡體   English   中英

更改ID后由JQuery觸發Javascript表單

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM