我正在加载一个显示多个元素的 php 页面,具体取决于用户(所以我不知道将显示多少个项目)。这些元素看起来像:
<div id='container_feed'>
<div id='feed_element' data-userid='4'>Random Dude</div>
<div id='feed_element' data-userid='5'>Random Dude 2</div>
</div>
我想在每个 div 上添加一个 click() 事件,并根据其用户 ID 使用 .load() 加载页面
我尝试了 child()、each() 和其他一些方法,但没有成功......
如何添加此事件?
谢谢。
最佳答案
为什么不像这样委托(delegate)所有点击:
/* You could also use '>div' if you can't guarantee the class name */
$('#container_feed').on('click', '.feed-element' , function() {});
这样,您最初只添加一个事件,但其中的所有 div 都将由单击事件处理。无需循环遍历每个元素,使用 .children
或 .each
甚至 $('#container_feed .feed-element')
。
委托(delegate)是你的 friend 。
关于javascript - JQuery向未知的div id添加点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18033839/