如何等到点击里面的功能? [英] How to wait till click inside function?

查看:111
本文介绍了如何等到点击里面的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对Javascript / jQuery进行一些初学者编码,并遇到问题。长篇小说:

I'm in process of some beginner coding on Javascript/jQuery and stuck with a problem. Long story short:


  1. 我有一个页面上的元素,应该忽略任何点击;

  2. 一次具体功能称为应该等到n点击;

  3. 功能应该执行一些代码;

  4. 完成后,元素应该再次忽略点击。 / li>
  1. I have one element on page which should ignore any clicks;
  2. Once specific function called it should wait until n clicks;
  3. Function should execute then some code;
  4. After all is done element should ignore clicks again.

我试图玩setInterval()/ clearInterval()但没有成功。

I tried to play around with setInterval() / clearInterval() but did not succeed.

请帮助我:)

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

P.S.: one way is to reload a page with the new code but it is not for my case.

UPD:

var select = function() {
    /*once called this function should enable clicks on <td>
    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/ 。希望这一小段代码能够澄清这个想法。

http://jsfiddle.net/superiorbanana/Z53EU/. Hope this small bit of code will clarify the idea.

推荐答案

我想你正在寻找jQuery的 on 关闭方法。

I think you're looking for jQuery's on and off methods.

在上使用绑定点击处理程序,然后将其关闭,当你完成它。因此,在您的情况下,您可以在触发后立即关闭点击处理程序。例如:

Bind a click handler with on, and then turn it off when you're done with it. So, in your case, you can turn a click handler off immediately after it's been triggered. For example:

$(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');
            }
        });
    });
});



或简单地



Or simply

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

查看你的 jsfiddle

这篇关于如何等到点击里面的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆