防止jQuery中的click事件多次触发 [英] Prevent click event in jQuery triggering multiple times

查看:112
本文介绍了防止jQuery中的click事件多次触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 jQuery内容切换器。一般来说,它工作正常,但它有一个问题。如果您多次单击侧面的链接,有时会看到多条内容。

I have created a jQuery content switcher. Generally, it works fine, but there is one problem with it. If you click the links on the side multiple times, multiple pieces of content sometimes become visible.

问题很可能出现在click事件中。以下是代码:

The problem most likely lies somewhere within the click event. Here is the code:

$('#tab-list li a').click(
    function() {
        var targetTab = $(this).attr('href');
        if ($(targetTab).is(':hidden')) {
            $('#tab-list li').removeClass('selected');
            var targetTabLink = $(this).parents('li').eq(0);
            $(targetTabLink).addClass('selected');
            $('.tab:visible').fadeOut('slow',
                function() {
                    $(targetTab).fadeIn('slow');
                }
            );
        }
        return false;
    }
);

我尝试为转换添加锁定,以便在转换发生时忽略更多点击,但无济于事。我还尝试使用以下内容阻止过度触发(如果某些内容已经过动画):

I have tried adding a lock to the transition so that further clicks are ignored as the transition is happening, but to no avail. I have also tried to prevent the transition from being triggered if something is already animating, using the following:

if ($(':animated')) {
    // Don't do anything
}
else {
   // Do transition
}

但它似乎总是认为事物是动画的。我有什么想法可以阻止多次触发动画?

But it seems to always think things are being animated. Any ideas how I can prevent the animation being triggered multiple times?

推荐答案

一个想法就是在开始时删除click事件你的函数,然后在动画结束时重新添加click事件,因此在持续时间内点击将没有任何效果。

One idea would be to remove the click event at the start of your function, and then add the click event back in when your animation has finished, so clicks during the duration would have no effect.

如果你有能力执行动画完成后的代码应该有效。

If you have the ability to execute code when the animation has finished this should work.

这篇关于防止jQuery中的click事件多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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