简体   繁体   English

jQuery on('click',...)不处理附加元素

[英]jQuery on('click', …) not working on appended element

I have a div that I append with the following code: 我有一个div,我附加以下代码:

function generateBall(){
    var colors = ["fe0ba5", "00c0ff", "21f1a5", "f13e21", "e819fb", "3ae319", "ff9900", "512e5e", "284184"];
    var width = $('.reaction_area').width() - 40;
    var height = $('.reaction_area').height() - 40;
    var a = Math.floor(Math.random()*(width - 40 + 1) + 40);
    var b = Math.floor(Math.random()*(height - 40 + 1) + 40);
    var size = Math.floor(Math.random()*(32 - 24 + 1) + 24);
    var color = colors[Math.floor(Math.random() * colors.length)];

    $('.reaction_area').append('<div class="ball_2" style="left: '+a+'px; top: '+b+'px; height: '+size+'px; width: '+size+'px; background: #'+color+'" data-id="'+wave+'"></div>');
}

And then I have this: 然后我有这个:

$('.ball_2').on('click', function(){
    $(this).remove();
    wave--;
});

And it's not working. 它不起作用。 I have other elements that I append like that and clicking them works, why this doesn't? 我有其他元素,我追加并点击它们工作,为什么这不?

I've tried also with $('document').on('click', '.ball_2', function(){ //code }); 我也尝试过$('document').on('click', '.ball_2', function(){ //code }); and it didn't work either. 它也没用。

That would be $(document) (without the quotes). 那将是$(document) (没有引号)。

$('.ball_2').on('click', ...) doesn't work because the element .ball_2 doesn't exist yet at the time of execution. $('.ball_2').on('click', ...)不起作用,因为在执行时元素.ball_2尚不存在。 However, $(document).on('click', '.ball_2', ...) works because it puts the handler on an ancestor element and takes advantage of a phenomenon called "event bubbling". 但是, $(document).on('click', '.ball_2', ...)工作原理是因为它将处理程序放在祖先元素上并利用了一种称为“事件冒泡”的现象。 In simple terms, an ancestor is considered clicked when a descendant is clicked. 简单来说,单击后代时会认为祖先被点击了。

Since element with class ball_2 is generated dynamically. 由于具有类ball_2元素是动态生成的。

$(document).on('click','.ball_2', function(){
    $(this).remove();
    wave--;
});

add following line in generateBall() function. 在generateBall()函数中添加以下行。 Because the div is created dynamically, so we should bind the function when it being create. 因为div是动态创建的,所以我们应该在创建函数时绑定它。 And this statement can let every '.ball_2' got it own remove function, assume there may be more than one '.ball_2'. 这句话可以让每个'.ball_2'都有自己的删除功能,假设可能有多个'.ball_2'。

$('.ball_2:last').on('click', function(){$(this).remove());});

use delegate : 使用委托

 $('.reaction_area').delegate('.ball_2', 'click', function (event) {

  $(this).remove();
    wave--;
});

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

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