[英]How to find dynamically added element by data attribute using jQuery?
There is an element to which is dynamically applied data attribute like this 有一个元素是这样动态应用的数据属性
var tr = $('<tr>');
tr.data('template_id', 5);
table.find('tbody').append(tr);
Here we have our tr on the table. 在这里,我们将tr放在桌面上。
... ...
Here we want to find our newly added tr by data attribute 在这里,我们希望找到我们新添加的tr by data属性
var tr = table.find('[data-template_id="5"]');
console.log(tr) // tr.length = 0;
Unfortunately, we have no found tr this way. 不幸的是,我们没有找到这种方式。
Why it is getting this result? 为什么会得到这个结果?
The issue you have is that data-*
attributes added via jQuery are stored in its internal cache. 您遇到的问题是通过jQuery添加的
data-*
属性存储在其内部缓存中。 They are not available as attributes in the DOM. 它们不能作为DOM中的属性使用。 With that in mind, you can use
filter()
to achieve what you require: 考虑到这一点,您可以使用
filter()
来实现您的需求:
var $tr = table.find('tr').filter(function() {
return $(this).data('template_id') == 5;
});
console.log($tr.length);
尝试tr.attr("data-template_id", 5)
而不是tr.data('template_id', 5)
。
我想你可以用
tr.attr('template_id', 5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.