我读过这个,所以这不是复制的。所有建议的解决方案都不起作用,jQuery如何基于数据属性值找到一个元素?
以下是我在Chrome控制台上所做的工作:
$('table#ct_ennemies_2 td').each(function() {
var t=$(this).data('to-shoot'); console.log(t == "1")
});然后我得到一个结果:一个单元格被标记为data('to-shoot') = 1。太棒了。现在,如果我试图查找by数据属性,如下所示:
$('table#ct_ennemies_2 td[to-shoot="1"]').each(function() {
console.log($(this))
});我得到了一个空洞的结果:
[]如果我试着的话
$('table#ct_ennemies_2 td[to-shoot=1]').each(function() {
console.log($(this))
});我得到了一个空洞的结果:
[]在Chrome的控制台日志中,您可以这样做:
>> $('table#ct_ennemies_2 td').first().data('to-shoot','1');
[<td ...blablah >@</td>]
>> $('table#ct_ennemies_2 td').first().data();
Object {toShoot: "1"}
>> $('table#ct_ennemies_2 td').first().data('to-shoot');
"1"
>> $('table#ct_ennemies_2 td[to-shoot="1"]');
[]
>> $('table#ct_ennemies_2 td[to-shoot]');
[]
>> $('table#ct_ennemies_2 td[data-to-shoot]').each(function() { console.log($(this)) });
[]
>> $('table#ct_ennemies_2 td[data-to-shoot=1]').each(function() { console.log($(this)) });
[]
>> $('table#ct_ennemies_2 td[data-to-shoot="1"]').each(function() { console.log($(this)) });
[]
>> $('table#ct_ennemies_2 td[data-toShoot="1"]').each(function() { console.log($(this)) });
[]
>> $('table#ct_ennemies_2 td[toShoot="1"]').each(function() { console.log($(this)) });
[]
>> $('table#ct_ennemies_2 td[toShoot=1]').each(function() { console.log($(this)) });
[]
>> td = $('#ct_ennemies_2 td').filter(function() {
>> return $(this).data('to-shoot') === 1;
>> });
[]
>> td
[]我的问题是:如何正确地应用一个过滤器,该过滤器返回包含数据td的预期to-shoot=1
发布于 2014-04-18 19:53:13
data属性以data-开头
$('table#ct_ennemies_2 td[data-to-shoot=1]')注意事项:只有当您在标记中或通过attr('data-to-shoot', 1)手动添加数据属性时,这才有效。如果它是通过data('to-shoot', 1)应用的,您将需要使用账单‘应答。
例琴
小提琴内容:
<div class="test"></div>
$(function(){
var d = $('div.test');
d.data('to-shoot', 1);
alert($('div[data-to-shoot=1]').length); // 0
d.attr('data-to-shoot', 1);
alert($('div[data-to-shoot=1]').length); // 1
var divs = $('div').filter(function(){
return $(this).data('to-shoot') == 1;
});
alert(divs.length); // 1
});发布于 2014-04-18 19:55:38
我将使用filter,因为.data不将数据应用于实际属性,而是应用于内部哈希表。
var $td = $('#ct_ennemies_2 td').filter(function() {
return $(this).data('to-shoot') === 1;
});此外,宠物恼怒,table之前的id选择是不必要的。
https://stackoverflow.com/questions/23161234
复制相似问题