将数据属性条件语句传递到循环中会导致浏览器

时间:2018-01-15 19:52:09

标签: javascript jquery

处理代码,如果您点击某些内容并且点击的链接的数据属性与某个部分不匹配,请隐藏它。我试图通过循环遍历与所点击链接的数据属性不匹配的标题元素来尝试这样做。

以下是我的意图的评论代码:

var titles = document.querySelectorAll(".authors-titles")
$(".filter-item").click(function(e) {
  e.preventDefault();

  // get data attribute of clicked link
  var targetLetter = $(this).attr("data-letter");

  // I try to loop through only the titles with data attributes that dont match the clicked link
  // I'm not sure about implementation but basically for titles who aattributes are not equal to the one gotten through the link
  for (var i = 0; i < titles.dataset != targetLetter; i++) {
    // hide the elements that get returned in this loop, in this case the non matched data attributes
    $(".authors-titles").css("display", "none");
  }
});

标记样本:

<ul id="filter">
        <li><a data-letter="a" href="#" class="filter-item">a</a></li>
        <li><a data-letter="b" href="#" class="filter-item">b</a></li>
        <li><a data-letter="c" href="#" class="filter-item">c</a></li>
      </ul>

<section data-title="a" class="authors-titles">
      <span class="alphabet">#</span>
      <div class="filter-item-grid">
        <div class="filter-item">
          <h3 class="filter-title">1984</h3>
          <p>By: <a href="#">George Orwell</a> </p>
        </div>
        <div class="filter-item">
          <h3 class="filter-title">2001: A Space Oddyseey</h3>
          <p>By: <a href="#">Author C. Clark</a> </p>
        </div>
      </div>
    </section>

所以基本上我真正想做的就是看看数据字母和数据标题是否匹配,然后将其隐藏起来。

我的主要问题是此代码会触发无限循环并完全崩溃我的浏览器,但我不明白为什么。我尝试将length添加到此行:

for (var i = 0; i < titles.length.dataset != targetLetter; i++) {

但我得到的结果相同。

1 个答案:

答案 0 :(得分:1)

HTMLElement.dataset是自定义数据属性的对象。

$(".filter-item").click(function(e) {
  e.preventDefault();
  var letter = this.dataset.letter;
  // loop through the sections
  $(".authors-titles").each(function () {
    // show section only if title is equal to letter
    $(this).toggle(this.dataset.title === letter);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="filter">
        <li><a data-letter="a" href="#" class="filter-item">a</a></li>
        <li><a data-letter="b" href="#" class="filter-item">b</a></li>
        <li><a data-letter="c" href="#" class="filter-item">c</a></li>
      </ul>

<section data-title="a" class="authors-titles">
a</section>

<section data-title="b" class="authors-titles">
b</section>

<section data-title="c" class="authors-titles">
c</section>

此外,如果您使用的是jQuery,则无需使用document.querySelector *。