在我正在开发的应用中,我试图将动态生成的元素(搜索结果)列表中的特定动态生成的元素作为目标。
每个元素都有一个带有生成的ID(数据库中的主键)的按钮。
我尝试使用这篇文章:How do I attach events to dynamic HTML elements with jQuery?,但它不适合我的情况。
HTML代码:
<div id="search-result">
//example of generated element
<div>
username(<user_id>)
<button id="<user_id>">Uitnodigen</button>
</div>
//end of generated element
</div>
我已经设法使用来选择生成的元素
jQuery:
$("#search-result").on("click", "button", function(event) {
user_id=event.target.id;
$("#search-result").on("click", "button", function(event) {
user_id=event.target.id;
});
但是当我想调用元素时,例如使用:
$("#search-result").find("user_id").html("Loading...");
//or
$("#search-result").on("click", "#user_id", function(event) {
//code
});
但是这两种解决方案都不起作用。 .find()函数找不到动态生成的元素。 .on()函数需要一个事件,但是该事件先前已经被触发过。
是否会有不需要事件的.on()替代方案,或者可以找到动态生成的元素的.find替代方案。还是不同的解决方案?
答案 0 :(得分:0)
mitmdump -s local-redirect.py --no-http2 localhost
将成为HTML标签'user_id'
的选择器。这就是它与<user_id />
一起使用的原因:因为它是现有标签。要在jQuery中定位,应使用'button'
。
请尝试以下操作:
'#user_id'
我建议使用类名,以避免潜在的id重复。