如何使 jquery 单击事件仅在第一次单击时触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12885660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:05:19  来源:igfitidea点击:

How to make a jquery click event fire only on first click

jquery

提问by user1745398

I have two divs (.basic1 and .basic2). I want .basic1 to fadeout on click, and .basic2 to fade in which I have working wonderfully. The only problem is that once .basic2 fades in, if the user continues to click the link (.navbar1), it will fade in this div over and over. I know that I need to use the .bind() function, but I can't seem to figure out where in my code to put it. Thanks!

我有两个 div(.basic1 和 .basic2)。我希望 .basic1 在点击时淡出,而 .basic2 淡入,我已经很好地工作了。唯一的问题是,一旦 .basic2 淡入,如果用户继续点击链接(.navbar1),它会一遍又一遍地淡入这个 div。我知道我需要使用 .bind() 函数,但我似乎无法弄清楚在我的代码中放置它的位置。谢谢!

$(document).ready(function() {
    $('.navbar1').click(function(e){
        e.preventDefault();

        $('.basic2').hide().load('.basic2', function() {
            $(this).delay(600).fadeIn(1000);
            $('.basic1').fadeOut(1000);
        });
    });
});

回答by Blender

Use .one():

使用.one()

$('.navbar1').one('click', function(e) {

It unbinds the clickevent once you trigger it.

click一旦您触发它,它就会解除绑定事件。

If you don't want an element to be double-clicked, something like this should work:

如果您不希望双击某个元素,则应该使用以下方法:

$(document).on('click', '.navbar1:not(.clicked)', function() {
    // ...
});

To make .navbar1unclickable, just run $('.navbar1').addClass('clicked'). To make it clickable, do the opposite.

要使.navbar1不可点击,只需运行$('.navbar1').addClass('clicked'). 要使其可点击,请执行相反的操作。

回答by A.M.K

Please see jQuery one()for one-time event handlers. i.e.

请参阅 jQueryone()以获取一次性事件处理程序。IE

$(document).ready(function() {
    $('.navbar1').one('click', function(e){
        e.preventDefault();

        $('.basic2').hide().load('.basic2', function() {
            $(this).delay(600).fadeIn(1000);
            $('.basic1').fadeOut(1000);
        });
    });
});

回答by Ohgodwhy

jQuery provides the .one()method for this exactly.

jQuery正是为此提供了.one()方法。

$(document).ready(function() {
    $('.navbar1').one('click', function(e){
        e.preventDefault();
        $('.basic2').hide() 
        .load('.basic2', function() {
            $(this).delay(600).fadeIn(1000);
            $('.basic1').fadeOut(1000);
        });
    });
});

回答by Gibolt

Use modern Js events, with "once"!

使用现代 Js 事件,带有“一次”!

const navbar = document.getElementsByClassName("navbar1")[0];
navbar.addEventListener("click", function() {
    // Add one-time callback
}, {once : true});

Documentation, CanIUse

文档, CanIUse