如何等到内部function?

我正在使用Javascript / jQuery进行一些初学者编码并遇到问题。 长话短说:

  1. 我在页面上有一个元素应该忽略任何点击;
  2. 一旦调用它的特定function应该等到n次点击;
  3. 函数应该执行一些代码;
  4. 完成所有后,元素应该再次忽略点击。

我尝试使用setInterval()/ clearInterval(),但没有成功。

请帮我 :)

PS:一种方法是使用新代码重新加载页面,但这不适合我的情况。

UPD:

var select = function() { /*once called this function should enable clicks on  toggling its class to yellow and once both cells are yellow clicking should be disabled*/ }; $(document).ready(function(){ $("button[name=start]").click(function(){ select(); }); }); 

http://jsfiddle.net/superiorbanana/Z53EU/ 。 希望这一小段代码能够澄清这个想法。

我想你正在寻找jQuery的on- off方法。

将点击处理程序与on绑定,然后在完成后将其off 。 因此,在您的情况下,您可以在触发后立即关闭单击处理程序。 例如:

 $(document).ready(function () { var $tds = $('td'), // store td's count = $tds.length; // store # of td's $("button[name=start]").on('click', function (e) { // pass `e` so that it can be used to turn itself off $(this).off(e); // this function won't execute again // bind td clicking after button's clicked $tds.on('click', function (e) { $(this).addClass('clicked').off(e); // executed once per td // the if statement and the count is actually // not necessary; it's just to demonstrate // that all the click handlers have ended. count--; // count - 1 if (count === 0) { console.log('there are no more click handlers'); } }); }); }); 

或者干脆

 $(document).ready(function () { $("button[name=start]").on('click', function (e) { $(this).off(e); $('td').on('click', function (e) { $(this).addClass('clicked').off(e); }); }); }); 

查看你的jsfiddle上的代码。

只需存储变量中的点击次数,然后使用javascript进行检查。 像这样的东西:

 var x = 0; $('#button').click(function(){ x++; if (x == 5) { alert("hello"); } }); 

小提琴

我不确定你是否在寻找这个,

HTML

 click disabled 
enable click

jQuery的

 var count=0; $(".two").click(function(){ $(".one").text("click enabled"); $(".one").click(function(){ count++; if(count==5) { $(".one").text("click disabled"); $(".one").off("click"); } alert("click enabled"); }); }); 

小提琴演示

在上面的代码中,单击第一个跨度的单击事件将不会触发,直到单击第二个跨度。 仅在单击第二个跨度后绑定第一个跨度的单击事件。 还有一个点击计数器。 当计数器达到限制时,将使用off()删除第一个跨度的单击事件

您应该在开头设置事件侦听器以侦听该元素上的任何click事件。

一旦调用它的特定function应该等到n次点击;

“特定function”可以将变量设置为先前为假的“真”。 这就是click事件侦听器正在等待的内容。 变量为true后,计数器变量可以计算点击次数

点击;

一旦计数器达到所需的点击次数,您就可以执行任何您想要的操作:

 if(counter === n) { executeMe(); counter = 0; } 

如果间隔始终相同,您也可以使用“mod”。