我希望能够从另一个函数调用此函数,而不是像下面的代码中那样使用事件处理程序。而不是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;
}
};
})();
答案 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;
答案 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();
}