moused on mousedown没有处理动态生成的元素

所以我正在尝试创建像塔防一样的js / css“wave游戏”。 当来自第一波的所有预先产生的敌人都死亡时,它会产生第二波,依此类推。

到现在为止还挺好。 问题是我无法攻击在第二波内动态生成的怪物。

我曾经在类似的情况下尝试过.live(),但是它已被弃用了,所以我正在按照指示尝试.on()

$(’。enemy’)。on(’mousedown’,function(event){

//攻击代码

}

它适用于初始怪物(第一波),但它仍然没有在动态怪物(> =第二波)上工作

求救,伙计们好吗?

您需要在创建DOM时指定已存在的元素。 在参数中,指定要添加mousedown方法的元素。 通过简单地分配$('.enemy') ,它会将方法附加到已经存在于DOM中的方法。

 $('body').on('mousedown', '.enemy', function(event) { //attack code } 

正如Wex在评论中提到的,你应该使用容器的名称(包装.enemy元素的容器$('body')而不是写$('body') 。这样,当添加.enemy元素时,事件不需要泡沫一直到body标签。

绑定’.on()’仅适用于脚本运行之前创建的内容。 因此,一种解决方案是将事件绑定到父元素。

  $('.PARENT_ELEMENT').on('mousedown', '.enemy', function(event){ // your code here } 

应该这样做。

我做了这个谷歌像下拉建议搜索框,我遇到了类似于你的问题,在重新直接发生之前有建议消失。 我通过使用和修改vyx.ca来克服它:

 var mousedownHappened = false; var clicked_link; $("#search-box").blur(function(e) { if (mousedownHappened)// cancel the blur event { mousedownHappened = false; window.location.href = clicked_link; } else { // no link was clicked just remove the suggestions box if exists if ($('#search-btn').next().hasClass('suggestions')) { $(".suggestions").remove(); } } }); //attaching the event to the document is better $(document).on('mousedown', '.suggestions a', function() { clicked_link= $(this).attr('href'); mousedownHappened = true; });