jQuery - 选择具有相同属性值的多个元素

时间:2017-04-07 23:46:34

标签: jquery

我试图找到一个jQuery选择器,它获取具有特定属性值的每个元素 - 不一定是相同的属性,只是相同的属性值。例如,jQuery选择器会选择以下各项吗?

<h1 name="test"><h1>
<a id="test"></a>
<p data-attribute="test"></p>

我能想到的只是$("*").attr( "*", "test" ),但这不起作用。

1 个答案:

答案 0 :(得分:1)

这是一个非常奇怪的问题。它可以通过循环遍历每个dom属性的属性来完成,但我建议重新构建HTML,以便您可以使用[data-test=true],一个值为true的数据测试属性。

$("*").filter(function() {
  flag = false;
  $.each(this.attributes, function(i, attrib){
    if (attrib.value == "test") {
      flag = true;
    }
  });
  return flag;
}).css("background","red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 name="test">a<h1>
<a id="test">b</a>
<p data-attribute="test">c</p>
<p>don't highlight</p>

相关问题