需要帮助让这个关闭工作

时间:2014-02-19 04:15:01

标签: javascript

我希望能够从另一个函数调用此函数,而不是像下面的代码中那样使用事件处理程序。而不是element.onclick,我想做类似

的事情
window.myFunction = (function(){ //the rest of the closure code//}

我可以调用myFunction();从另一个函数,而不是必须单击按钮。

var element = document.getElementById('button');

element.onclick = (function() {
// init the count to 0
var count = 0;

return function(e) {
    //count
    count++;

    if (count === 3) {
        // do something every third time
        alert("Third time's the charm!");
        //reset counter
        count = 0;
    }
};
})();

2 个答案:

答案 0 :(得分:0)

这应该适合你:

var element = document.getElementById('button');

var f = (function() {
    var count = 0;

    return function(e) { //e is not really needed, but left in there anyway
      //count
      count++;

      if (count === 3) {
        // do something every third time
        alert("Third time's the charm!");
        //reset counter
        count = 0;
      }
  };
})();
element.onclick = f;

小提琴:http://jsfiddle.net/2eFD2/2/

答案 1 :(得分:0)

<强> LIVE DEMO

var element = document.querySelector('#button'),
    count = 0;

function myCountFunction(){
   count = ++count % 3; // loop count
   if ( !count ) {      // if count is 0
      alert("Third time's the charm!");
   }
}

//On click:
element.addEventListener('click', myCountFunction, false);


// Immediately:
myCountFunction(); // this will trigger the event once

// Inside some other function: 
function myOtherFunction(){
   myCountFunction();  
}