简体   繁体   English

再次使用函数后,带有++的jQuery会相乘

[英]jQuery adding with ++ multiplies after using function again

I made a function called test (for example), and it works like this: 我做了一个叫做test的函数(例如),它的工作原理如下:

function test(){
    var i = 0;

    $('.container').click(function(){
        $(this).append('<div class="element"></div>');
        $('.element').click(function(){
            if (i >= 10){
                $('this').remove();
            } else {
                i++;
            }
        });
    });
};
test();

When I click the class .container , a div appends with the classname .element . 当我单击类.container ,一个div附加了类名.element When I click this div, var i goes up, until reaching 10. Then the div called .element is removed. 当我单击该div时,var i会上升,直到达到10。然后删除了名为.element的div。

The problem is, is when I click .container again, after .element is removed, the i variable is acting like its clicked twice. 问题是,当我再次单击.container时,删除.element后, i变量的行为就像单击两次一样。 After that trice, and so on. 在那个骰子之后,依此类推。 How do I counteract this? 我该如何应对?

You need to attach event to dynamically added elements using .on() 您需要使用.on()将事件附加到动态添加的元素上

$('.container').click(function(){
        $(this).append('<div class="element"></div>');

    });

 $('body').on('click','.element',function(){
   if (i >= 10){
      $(this).remove();
   } else {
         i++;
   }
});

Also remove .element div event handler inside .container div 还要删除.container div中的.element div事件处理程序

Another way is to bind an element like this 另一种方法是绑定这样的元素

You can also use on / bind method to attached an event to dynamic elements. 您还可以使用on / bind方法将事件附加到动态元素。

$(document).on('click','.element',function(){
   if (i >= 10){
      $(this).remove();
   } else {
      i++;
   }
});

OR 要么

$(document).bind('click','.element',function(){
       if (i >= 10){
          $(this).remove();
       } else {
          i++;
       }
    });

You can define the click event for .element like below. 您可以为.element定义click事件,如下所示。

 var i = 0; function test() { $('.container').click(function() { $(this).append('<div class="element"></div>'); }); }; test(); $('body').on('click', '.element', function() { if (i >= 10) { $('this').remove(); } else { i++; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> Click Me! </div> 

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

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