![](/img/trans.png)
[英]How to check if the radio buttons has already bound with a “change” event handler
[英]Do not bind an event handler if has been already bound
我正在使用ajax調用某些表單,然后為每個按鈕綁定一個事件處理程序。 問題是...當我使用ajax調用新表單時,將再次為新元素調用事件處理程序,然后為先前元素添加兩次。 如何檢測事件處理程序是否已經在元素上並且不再綁定它?
function x(){
$("input:button").click(function(){
alert('is this called once?');
});
}
<input type='button' value='Disable me' />
<input type='button' value='Disable me' />
function x(){ $("input:button").click(function(){ alert('is this called once?'); }); } // calling event twice simulating an ajax calling: x(); x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type='button' value='Disable me' /> <input type='button' value='Disable me' />
一種實現方法是使用jQuery的off
函數刪除所有附加事件,然后附加它。
這確保只有一個click事件附加到元素。
示例片段:
function x() { $("input:button").off('click').on('click', function() { console.log('is this called once?'); }); } // calling event twice simulating an ajax calling: x(); x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='button' value='Disable me' /> <input type='button' value='Disable me' />
每次調用AJAX請求時,是否真的需要重新添加點擊處理程序? 如果沒有,請考慮如下修改代碼:
//Only call this once; new buttons will still trigger it $(document).on('click', 'input:button', function() { alert('is this called once?'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='button' value='Disable me' /> <input type='button' value='Disable me' />
通過將處理程序附加到文檔並提供選擇器( 'input:button'
),該功能僅在單擊按鈕時觸發,但將自動應用於在初始綁定后添加的任何新按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.