[英]jQuery .click() trigger event on non-existent html element
我有一個ID為“open”的HTML按鈕。 我已經添加了一個jQuery .click()
綁定到由ID選擇的HTML按鈕。 在.click()
綁定中,我將“open”的ID更改為“close”。 但是,即使ID已更改為“關閉”,隨后對“打開”按鈕的單擊仍然會觸發。 代碼如下:
的index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id="open">Open</button>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
index.js
$('#open').click(function() {
console.log("clicked");
$(this).attr('id', 'close');
});
https://jsfiddle.net/iHexBot/28tj1ywg/
我期待/希望只看一次控制台日志“點擊”。 但是,即使HTML元素ID不再“打開”,它也會在每次單擊按鈕時記錄“單擊”。 有人可以向我解釋為什么會發生這種情況,如果可能的話,如何解決這個問題?
如果您只想觸發一次,我會嘗試這樣做:
$('#open').one("click", function() {
console.log("clicked");
$(this).attr('id', 'close');
});
但是如果你要創建一個“切換”按鈕,我不會這樣做。 我會根據它是應該打開還是關閉來創建一個不同的事件,正如其他答案所示。
您可以將事件綁定到文檔而不是像這樣的元素
$(document).on('click', '#open', function() {
console.log('this will only be displayed as long as id is "open"');
});
請改用此腳本:
$('#open').bind('click', function() {
console.log("clicked");
$(this).attr('id', 'close').unbind('click');
});
這是在open
和close
之間切換的代碼
<button class="toggleButton" data-option="open">Open</button>
$(document).on('click','.toggleButton',function() {
if($(this).attr('data-option') == 'open') {
console.log('open');
// do something if "open" clicked;
$(this).text('Close');
$(this).attr('data-option','close');
}else{
console.log('close');
// do something if "close" clicked;
$(this).text('Open');
$(this).attr('data-option','open');
}
});
jsfiddle - https://jsfiddle.net/ygf1327m/
為此,你“應該”使用ONE()而不是取消綁定。 為了證明這一點,我已經編輯了你原來的JSFIDDLE。
jQuery(document).ready(function ($)
{
//the element to evaluate
var current_id= $("button#open");
alert("The ID of the button is: " + current_id.attr("id") );
current_id.one("click", function () {
//now once we click the button we have
current_id.attr('id', 'close');
alert("Now the ID is: " + current_id.attr('id') + " so we are changing it\'s text too... " );
//reflect the change
current_id.text("Close");
});
});
的jsfiddle:
https://jsfiddle.net/28tj1ywg/4/
jQuery將在瀏覽器加載時綁定.click()
事件,而不是在每次單擊后重新綁定它。
你會想要.unbind()
這個事件應該排除你的問題。
$('#open').click(function() { console.log("clicked"); $(this).attr('id', 'close'); $(this).unbind(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="open">Open</button>
原因是在執行事件處理程序時,其上下文(即“this”對象)與定義上下文不同。 另請參見如何將此上下文傳遞給事件處理程序?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.