jQuery不选择jQuery添加元素 [英] jquery does not select jquery added element

查看:111
本文介绍了jQuery不选择jQuery添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个jquery函数,当单击类"ajaxsubnote"时会执行某些操作

So I have a jquery function that does something when class 'ajaxsubnote' is clicked

$('.ajaxsubnote').click(function(){
     //do something....
})

但是用户可以通过jquery动态添加类为'ajaxsubnote'的元素.我的问题是这些动态添加的元素在单击时似乎没有调用上面的函数,而最初在DOM上的元素却会调用...

But the user can add elements with class 'ajaxsubnote' dynamically via jquery. My problem is these dynamically added elements, when clicked, don't seem to call the above function, whereas the ones originally on the DOM do...

有什么办法解决吗?

推荐答案

您应该使用委托事件方法来处理动态元素.见下文

You should use delegated event method to handle dynamic elements. See below,

// v--- replace document with closest parent container that exist in DOM
$(document).on('click', '.ajaxsubnote', function(){
     //do something....
})

对于较旧的版本,请使用委托,

For older versions use delegate,

// v--- replace document with closest parent container that exist in DOM
$(document).delegate('.ajaxsubnote', 'click', function(){
     //do something....
})

这篇关于jQuery不选择jQuery添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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