moused在mousedown上没有处理动态生成的元素 [英] Jquery on mousedown not working on dynamically generated elements

查看:76
本文介绍了moused在mousedown上没有处理动态生成的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So i'm trying to create a js/css "wave game" like tower defense ones. When all the pre-generated enemys from first wave are dead, it spawns the second wave and so on.

到目前为止一切顺利。
问题是我无法攻击在第二波中动态生成的怪物。

So far so good. The problem is that i just can't attack mobs dynamically spawned within second wave.

我曾经在类似的情况下尝试.live(),但是不推荐使用,所以我正按照指示尝试.on()

I used to try .live() in similar cases, but its deprecated, so i'm trying .on(), as instructed


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

$('.enemy').on('mousedown' , function(event) {


//攻击代码

//attack code

}

它适用于初始怪物(第一波),但它仍然不适用于动态怪物(> =第二波)

Its working fine for initial mobs (1st wave) but it still just not working on dynamic mobs (>= 2nd wave)

帮助,伙计们,好吗?

推荐答案

你在创建DOM时需要指定一个已存在的元素。在参数中,指定要添加mousedown方法的元素。只需指定 $('。enemy'),它会将方法附加到已经存在于DOM中的方法。

You need to specify an element that is already there when the DOM is created. In the parameters, you specify the elements you want to add the mousedown method. By simply assigning $('.enemy'), it will attach the method to those that are already present in the DOM.

$('body').on('mousedown', '.enemy', function(event) {

    //attack code

}

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

As Wex mentioned in the comments, instead of writting $('body') you should use the container's name (the container which wraps the .enemy elements. This way, when a .enemy element is added, the event doesn't need to bubble all the way up to the body tag.

这篇关于moused在mousedown上没有处理动态生成的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆