隐藏指定数据属性的元素

时间:2015-06-11 10:00:04

标签: javascript jquery

我尝试根据点击的链接文本制作过滤器,基于其data-firstname属性隐藏div,该属性与当前点击元素匹配,但遗憾的是没有工作,下面是我的代码段。任何线索,想法,建议,帮助,建议都将不胜感激,谢谢!



$(document).ready(function(){
  $("a").click(function(){
    var thistext = $(this).text();
    //hide all div first
    $("div").hide();
    //show the div that has the match data-firstletter content of the selected link text
    $("div[data-firstletter='" + thistext +"' ]").hide();
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#">A</a>
<a href="#">B</a>
<a href="#">C</a>

<div data-firstletter="A">
a box that has a data firstletter attribute of A
</div>

<div data-firstletter="A">
a box that has a data firstletter attribute of A
</div>

<div data-firstletter="A">
a box that has a data firstletter attribute of A
</div>

<div data-firstletter="B">
a box that has a data firstletter attribute of B
</div>

<div data-firstletter="B">
a box that has a data firstletter attribute of B
</div>

<div data-firstletter="C">
a box that has a data firstletter attribute of C
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

您在两个对象上使用hide() - 对show()属性选择的元素使用data。试试这个:

&#13;
&#13;
$(document).ready(function() {
  $("a").click(function() {
    var thistext = $(this).text();
    $("div").hide().filter("[data-firstletter='" + thistext + "']").show();
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#">A</a>
<a href="#">B</a>
<a href="#">C</a>

<div data-firstletter="A">
  a box that has a data firstletter attribute of A
</div>

<div data-firstletter="A">
  a box that has a data firstletter attribute of A
</div>

<div data-firstletter="A">
  a box that has a data firstletter attribute of A
</div>

<div data-firstletter="B">
  a box that has a data firstletter attribute of B
</div>

<div data-firstletter="B">
  a box that has a data firstletter attribute of B
</div>

<div data-firstletter="C">
  a box that has a data firstletter attribute of C
</div>
&#13;
&#13;
&#13;

请注意,我链接了选择器并使用filter()将另一个查询保存到DOM。