简体   繁体   English

jQuery中事件内的事件

[英]Events inside events at jQuery

This might be a very basic question but I couldn't find an answer. 这可能是一个非常基本的问题,但我找不到答案。 (I might be looking for the wrong terms...) (我可能正在寻找错误的条款......)

Sometimes I feel that I need to add an event inside another event in order to share variables, for example. 有时我觉得我需要在另一个事件中添加一个事件,以便共享变量,例如。 But I've realized the events inside can be fired multiple times depending on the times the parent event has been fired. 但我已经意识到内部事件可以多次触发,具体取决于父事件被触发的时间。

Here's a basic example of what I'm talking about: http://jsfiddle.net/mRc9K/ 这是我正在谈论的基本例子: http//jsfiddle.net/mRc9K/

$('.demo').click(function(){
    $('.hidden').show(function(){
        $('#link').click(function(){
            alert("Clicked"); //fired multiple times
            $(this).parent().hide(); 
        });
    });
});

If you click more than once in the "First Click" you will see how the second event is fired multiple times. 如果您在“首次点击”中多次单击,您将看到多次触发第二个事件。

I am not looking for that behavior. 我不是在寻找那种行为。 I know I can avoid it using delegation making use of .on() but... isn't there any other way to avoid the events inside to be fired multiple times? 我知道我可以使用.on() 使用委托来避免它但是......是否有任何其他方法可以避免多次触发内部事件?

Thanks. 谢谢。

A solution would be to use jQuery's one() method. 解决方案是使用jQuery的one()方法。

one() - Attach a handler to an event for the elements. one() - 将处理程序附加到元素的事件。 The handler is executed at most once per element. 每个元素最多执行一次处理程序。

In this case, it would be: 在这种情况下,它将是:

$('#link').one('click', function(){
   alert("Clicked"); //fired multiple times
   $(this).parent().hide(); 
});

jsFiddle example here. 这里是jsFiddle的例子。

Just use .one() , which binds the event just once per element: 只需使用.one() ,它每个元素只绑定一次事件:

$('.demo').click(function () {
    $('.hidden').show(function () {
        $('#link').one('click', function () {
            alert("Clicked");
            $(this).parent().hide();
        });
    });
});

Demo and Documentation 演示文档

You can also use a variable as a flag: Live DEMO 您还可以使用变量作为标志: Live DEMO

var clicked = false;
$('.demo').click(function(){
    clicked = true;
    $('.hidden').show(function(){
        $('#link').click(function(){
            if(clicked == true){
                alert("Clicked");
                $(this).parent().hide();
                clicked = false;
            }
        });
    });
});

You can either fire it once like all others said or you can unbind the click event every time (Just a different aproach) 你可以像所有其他人一样开火一次,也可以每次解开点击事件(只是一个不同的方法)

$('.demo').click(function(){
    $('.hidden').show(function(){
        $('#link').click(function(){
            alert("Clicked");
            $(this).parent().hide();
            $('#link').unbind('click');
        });
    });
});

jsfiddle :). jsfiddle :)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM