2015-11-02 113 views
2

我有一個ID爲「open」的HTML按鈕。我已經添加了一個jQuery .click()綁定到由ID選擇的HTML按鈕。在.click()綁定中,我將「打開」的ID更改爲「關閉」。但是,即使ID已更改爲「關閉」,後續點擊「打開」按鈕仍會觸發。代碼如下:jQuery .click()在不存在的html元素上觸發事件

的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不再「打開」,每次單擊按鈕時都會記錄「單擊」。有人可以向我解釋爲什麼會發生這種情況,如果可能的話,如何解決這個問題?

+3

您必須在事件再次綁定,或使用代表團的功能就像() – FLX

+0

然後你要綁定到$(「#閉」),並做了關閉功能?還是你只是這樣做,以便事件只觸發一次? – Dhunt

回答

0

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>

2

如果你只是想觸發一次我想嘗試這樣的:

$('#open').one("click", function() { 
    console.log("clicked"); 
    $(this).attr('id', 'close'); 
}); 

,但如果你正在創建一個 '切換'按鈕我不會這樣做。我會創建一個事件,根據是否應該打開或關閉而採取不同的行動,正如其他答案所暗示的。

1

使用此腳本:

$('#open').bind('click', function() { 
    console.log("clicked"); 
    $(this).attr('id', 'close').unbind('click'); 
}); 
1

下面是切換openclose之間

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

2

您可以綁定的事件,而不是元素的文檔,像這樣

1

爲此目的,您「應該」使用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/

相關問題