jquery on动态生成的子动态生成的子事件

时间:2017-12-19 22:20:45

标签: javascript jquery html dynamic mouseenter

我有一个动态添加的div,我想为已在另一个标签中动态添加的图像设置一个mouseenter事件。被添加的div看起来像这样:

<div class="chat_box">

</div>

在添加内容后看起来像这样:

<div class="chat_box">
  <p class="chat">text here <img class="emote" src="emote.png"> more text</p>
</div>

我想用一个表情符号的图像有一个mouseenter事件,但是我无法让它工作。

我尝试了以下内容:

$('.chat_box').on('mouseenter', '.chat', function(){
  alert();
});

并且它有效,但如果我尝试使用子选择器

$('.chat_box').on('mouseenter', '.chat > .emote', function(){
  alert();
});

$('.chat_box').on('mouseenter', '.chat > img', function(){
  alert();
});

它没有用。

1 个答案:

答案 0 :(得分:0)

这是之前由.live()提供的,但该函数已合并到.on()...它会创建一个事件监视器。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="chat_box"></div>

<button>Add</button>

<script>
$('button').click(function(){
    $('<div class="chat"><img width=10 height=10 class="emote"></div>').appendTo('.chat_box');
});
$('.chat_box').on('mouseenter', 'img.emote', function(){ alert('test'); });           
</script>

只需定位父对象,让它注意预期的孩子。