如何只注册一次点击事件?

Fly*_*Cat 1 javascript jquery

我正在尝试将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();
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我希望我能很好地解释我的问题.谢谢您的帮助!

Nel*_*son 7

做就是了:

$('#aButton').one('click', function(){
     alert('click')
});
Run Code Online (Sandbox Code Playgroud)