如何使用基于数据属性的jQuery显示元素

时间:2015-07-09 08:12:44

标签: jquery

我需要能够根据匹配的数据属性值显示列表中的某些元素。

例如:

<ul>

    <li data-album-id-trigger="1" class="album-trigger">Show / Hide album</li>
    <ul data-album-id="1" class="album-list" style="display:none">
        <li>Track 1</li>
        <li>Track 2</li>
        <li>Track 3</li>
    </ul>

    <li data-album-id-trigger="2" class="album-trigger">Show / Hide album</li>
    <ul data-album-id="2" class="album-list" style="display:none">
        <li>Track 1</li>
        <li>Track 2</li>
        <li>Track 3</li>
    </ul>

</ul>

所以基本上,当您点击.album-trigger值为data-album-id-trigger的{​​{1}}元素时,.album-list的{​​{1}}值为1将显示为使用jQuery {{ 1}}方法。

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

尝试

&#13;
&#13;
//click handler for album-trigger
$('.album-trigger').click(function() {
  //get the value of data-album-id-trigger
  var tid = $(this).data('album-id-trigger');
  //hide all album-list then show only the one's with data-album-id same as the clicked value
  var $current = $('.album-list[data-album-id="' + tid + '"]').toggle();
  $('.album-list').not($current).hide()

  //if you don't want to hide the previous items
  //$('.album-list[data-album-id="' + tid + '"]').toggle();
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>

  <li data-album-id-trigger="1" class="album-trigger">Show / Hide album</li>
  <li data-album-id="1" class="album-list" style="display:none">
    <ul>
      <li>Track 1</li>
      <li>Track 2</li>
      <li>Track 3</li>
    </ul>
  </li>

  <li data-album-id-trigger="2" class="album-trigger">Show / Hide album</li>
  <li data-album-id="2" class="album-list" style="display:none">
    <ul>
      <li>Track 1</li>
      <li>Track 2</li>
      <li>Track 3</li>
    </ul>
  </li>

</ul>
&#13;
&#13;
&#13;