ShuffleJS 无法读取 属性 'textContent' of null

ShuffleJS cannot read property 'textContent' of null

我正在学习 ShuffleJS 在项目中使用它,但我 运行 遇到 search 功能的问题。当我尝试搜索我的项目时,我不断收到此错误:

Cannot read property 'textContent' of null

我从 docs 中获取了搜索代码,但它似乎对我不起作用。

这是我的搜索功能的一些代码:

HTML

<section class="search">
  <div class="container">
    <div class="row">
      <div class="col-12">
        <div class="form-group">
          <input type="search" id="search" class="form-control">
        </div>
      </div>
    </div>
  </div>
</section>

<section>
  <div class="container">
    <div class="row" id="grid">
      <div class="box green" data-groups='["green"]' data-title="blue">green</div>
      <div class="box red" data-groups='["red"]' data-title="red">red</div>
      <div class="box green" data-groups='["green"]' data-title="blue">green</div>
      <div class="box red" data-groups='["red"]' data-title="red">red</div>
      <div class="box green" data-groups='["green"]' data-title="blue">green</div>
      <div class="box red" data-groups='["red"]' data-title="red">red</div>
      <div class="col-md-2 my-sizer"></div>
    </div>
  </div>
</section>

JS

const Shuffle = window.Shuffle;
const element = $('#grid');
const sizer = $('.my-sizer');

const shuffle = new Shuffle(element, {
  itemSelector: '.box',
  sizer
})

$('#search').on('keyup', (e) => {
  var searchText = e.target.value.toLowerCase();

  shuffle.filter((element, shuffle) => {
    var titleElement = element.querySelector('.box');
    var titleText = titleElement.textContent.toLowerCase().trim(); // <= this is where the error is thrown

    return titleText.indexOf(searchText) !== -1;
  });
})

我也尝试复制并粘贴他们的示例 JS 文件 here,但我遇到了与上述相同的错误。

我还在 CodePen!

中复制了上面编写的代码

谁知道问题出在哪里?感谢您的帮助!

在您的过滤函数中,element 似乎已经是 div 和 class box。因此,无需在 element 中查找具有 class box 的元素,因为您已经找到了它。

所以你可以替换

    var titleElement = element.querySelector('.box');
    var titleText = titleElement.textContent.toLowerCase().trim(); // <= this is where the error is thrown

    var titleText = element.textContent.toLowerCase().trim();