Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

javascript - Prevent click event in jQuery triggering multiple times

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...