簡體   English   中英

jQuery如何基於數據屬性值(v2)查找元素?

[英]jQuery how to find an element based on a data-attribute value (v2)?

我已經讀過了,所以這不是重復的。 提出的所有解決方案均無效jQuery如何基於數據屬性值查找元素?

這是我在Chrome控制台上所做的事情:

$('table#ct_ennemies_2 td').each(function() {
    var t=$(this).data('to-shoot'); console.log(t == "1")
});

然后我得到一個結果:一個單元格被標記為data('to-shoot') = 1 大。 現在,如果我嘗試按如下所示通過data屬性查找:

$('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的過濾器,該td包含to-shoot=1的數據to-shoot=1

data屬性始於data-

$('table#ct_ennemies_2 td[data-to-shoot=1]')

注意 :僅當您在標記中或通過attr('data-to-shoot', 1)手動添加data屬性時,此方法才有效。 如果它是通過data('to-shoot', 1) ,則需要使用Bills的答案。

小提琴的例子

小提琴內容:

<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
});

我將使用filter因為.data不會將數據應用於實際屬性,而是應用於內部哈希表。

var $td = $('#ct_ennemies_2 td').filter(function() {
  return $(this).data('to-shoot') === 1;
});

另外,請耐心等待,不需要您的id選擇器之前的table

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM