如何触发对动态添加的元素的点击

时间:2019-04-10 13:24:16

标签: jquery

此元素是动态生成的。是否可以触发元素单击?

<a unselectable="on" href="javascript:;" onclick="return false;" class="xxx" role="button" aria-haspopup="true">
  <span unselectable="on" class="xxx2">
    New<br>
    Item
    <span unselectable="on" class="xxx3">
      <img unselectable="on" src="xxx">
    </span>
  </span>
</a>

2 个答案:

答案 0 :(得分:0)

使用trigger('click')来获得参考文献http://api.jquery.com/trigger/,希望这会有所帮助

$(document).on('click','.xxx',function(e){
   console.log('link has been clicked') 
})

$('.xxx').trigger('click')   // dynamic click event on link
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a unselectable="on" href="javascript:;" onclick="return false;" class="xxx" role="button" aria-haspopup="true"><span unselectable="on" class="xxx2">New<br>Item<span unselectable="on" class="xxx3"><img unselectable="on" src="xxx"></span></span></a>

答案 1 :(得分:0)

如果您尝试询问“ 是否可以在动态元素上附加元素的点击?”,然后

$('body').on('click', function(evt) {
    // Check if its the proper element. Here its anchor tag with class 'xxx'
    if (evt.target.nodeName === 'A' && evt.target.classList.contains('xxx')) {
       // Anchor tag is clicked
    }
}, true);

如果您在事件冒泡期间需要检测多个元素,这将很有用。