[英]Strange behavior with on/off click and jQuery?
因此,我嘗試使用鏈接單擊將按鈕添加到div中,然后能夠單擊這些按鈕將其刪除,然后重新啟用要再次單擊的原始鏈接,以便可以添加和刪除無數次。 我大多數情況下都能正常工作,但是嘗試重新啟用click功能后,我得到了奇怪的行為。
1)您需要單擊兩次鏈接以重新添加按鈕,然后
2)有時我現在在div中獲得附加按鈕的多個實例。
這是我的代碼:
var selections = ' ';
function add_Button() {
jQuery(".form-unselected").click(function (e) {
jQuery(this).removeClass('form-unselected').addClass('selected').off('click');
var title = jQuery(this).attr("title");
var id = jQuery(this).attr("href");
selections += title + ', ';
var button_content = jQuery('<button class="content-button">').html(title).attr("title", title).attr("id",id);
event.preventDefault();
$( "#selected-items" ).append(button_content);
console.log(selections);
});
}
add_Button();
jQuery(document).on('click','.content-button', function(e){
var removed_content = jQuery(this).attr("title") + ', ';
selections = selections.replace(removed_content,'');
var href = jQuery(this).attr("id");
jQuery(".add-to-form[href='"+ href +"']").addClass('form-unselected').removeClass('selected').on('click', add_Button );
jQuery(this).remove();
console.log(selections);
});
selections變量是用逗號分隔的值列表,用於其他目的,但是我也在那里找到了重復項。 提前致謝!
您不應動態添加和刪除點擊處理程序。 最初將單擊處理程序添加到所有按鈕。 然后單擊時,您可以查詢狀態並做出決定。
此外,還有一個未知的參考event
,該event
與參數e
不匹配。
而且,重復jQuery(this)
非常昂貴。 將此值存儲在局部變量中,然后引用它。 下面的代碼演示了所有更改。
var selections = ' ';
jQuery(".form-unselected").click(function (e) {
var $this = jQuery(this);
if ($this.hasClass("selected")) {
return;
}
$this.removeClass('form-unselected').addClass('selected');
var title = $this.attr("title");
var id = $this.attr("href");
selections += title + ', ';
var button_content = jQuery('<button class="content-button">').html(title).attr("title", title).attr("id",id);
e.preventDefault();
$("#selected-items").append(button_content);
console.log(selections);
});
jQuery(document).on('click','.content-button', function(e) {
var $this = jQuery(this);
var removed_content = $this.attr("title") + ', ';
selections = selections.replace(removed_content,'');
var href = $this.attr("id");
jQuery(".add-to-form[href='"+ href +"']").addClass('form-unselected').removeClass('selected');
$this.remove();
console.log(selections);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.