Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

jquery event handler to execute only once the is bound to multiple elements

I want to have an event handler that executes only once and then unbinds itself from all the elements it was bound to.

I know of .one() but when using it "The handler is executed at most once per element".

Is there a "built-in" way to bind an event handler to multiple elements and have it removed automatically from all of the once it is executed on any one of them?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Easy. Just unbind the event handler inside the callback function. Like this:

$('p').on('click', function(){
  alert('I appear only one time');
  $('p').off('click'); // Removes the event. So, it will never be executed again.
})

This script will remove all events of type click, and that is a bit aggresive. Check the documentation for off and unbind for more info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...