簡體   English   中英

如何只注冊一次點擊事件?

[英]How to register click event only once?

我試圖將click事件一次注冊到項目中的元素。

我的代碼簡略,基本上我的結構如下所示:

function objectParent(){

}

objectParent.prototype.click=function()(

   $('#create').click(function(){
     var var1=new objectchild();
         var1.add();
   })

}

function objectchild(){

}

objectchild.prototype.add=function()(

  //The '#aButton' click event will be registered 4 times if the '#create' button is clicked 4 times.
  //so the alert will pop 4 times when 'aButton' is clicked which is not what I wanted.

  //I can use $('#aButton').unbind('click') to remove the click event but I have many buttons in my project
  //and I want to have better solution for this.

  $('#aButton').click(function(){
     alert('click')
   })

}

var test=new objectParent()
    test.click();

html

<a id='create' href='#'>test</a>

//everytime this <a> is clicked, it will create a new objectchild object 
//after click 4 times of this button and click 'aButton', it will pop the alert box 4 times
//I know it register click event 4 times to the 'aButton' 
//I only want to pop the alert box once.

//I can use $('#aButton').unbind('click); to remove the click event but I have many many buttons in my codes
//ex bButton, cButton...etc. I want to have a better approach for my codes.

<a id='aButton' href='#'>button</a>

我希望我能很好地解釋我的問題。 謝謝您的幫助!

做就是了:

$('#aButton').one('click', function(){
     alert('click')
});

嘗試:

var clickHandler = function(event) {
  $('#element').unbind('click', clickHandler);
  ...
} 
$('#element').on('click', clickHandler);

http://jsfiddle.net/zYGhz/

我認為納爾遜(Nelson)和亞歷克斯(Alex)必須誤解了飛貓(FlightCat)的要求...
one()方法只能確保已注冊的處理程序僅被調用一次,
但是如果開發人員多次調用one()方法(就像在FlyingCat的場景中一樣),

 for (var i = 0; i < 3; i++) {
     $("#element").one(function() {
          alert(1);
     })
 }

單擊每個注冊的處理程序一次,因此問題仍未解決。
Kolink的答案是正確的,您必須進行一些小的更改。

到目前為止,最簡單的方法是確保在附加新的objectchild的click功能之前,將其刪除。 還有其他方法,但是代碼會更多。

objectchild.prototype.add = function(){
    $('#aButton').off('click.x').on('click.x'function(){
        alert('click');
    });
};

.x用於命名事件的名稱空間。 這允許.off('click.x')進行操作而不會影響代碼中其他位置可能附加的其他單擊處理程序。 如果沒有附加其他單擊處理程序,則嚴格不需要命名空間,但這不會造成任何危害。

您可能希望將.x替換為更有意義的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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