简体   繁体   English

jQuery仅执行一次功能

[英]Jquery execute function only once

I have code: 我有代码:

$(Page).on('click', '*', function(e)
{
    myFunction();
}

function myFunction(){//do something...}

I would like the code in the function to be done only once, now when I click, for example, 5 times, the code from the function myFunction() will be executed 5 times. 我希望函数中的代码仅执行一次,现在,例如,单击5次后,来自函数myFunction()的代码将被执行5次。 I don't want to change on('click', '*', ... 我不想更改on('click', '*', ...

Use jQuery's one method. 使用jQuery的one方法。

Description: Attach a handler to an event for the elements. 说明:将处理程序附加到元素的事件。 The handler is executed at most once per element per event type. 每个事件类型的每个元素最多只能执行一次处理程序。

Simply change your .on to .one . 只需将.on更改为.one

$(Page).one('click', '*', function(e) {
  myFunction();
});

function myFunction() {
  // do something
}

Here's the documentation for one 下面是文档one

You can use the function $.one 您可以使用功能$.one

$(Page).one('click', '*', function(e)
     myFunction();
});

Or, better: 或更好:

$(Page).one('click', '*', myFunction);

Be careful with that event delegation who will bind the event click to the whole set of elements within the DOM tree of Page . 请小心事件委托,它将事件单击绑定到Page的DOM树中的整个元素集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM