重写 $.data() 函数而不使用 jQuery

Rewriting the $.data() function without jQuery

本文关键字:jQuery 函数 data 重写      更新时间:2023-09-26

我想从下面删除jQuery。据我了解,$.data() 函数用于存储数据。

我有点困惑如何做到这一点。

document.querySelector('.sheet').addEventListener('scroll', function() {
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
      // do stuff
    }, 250));
});

我认为您正在寻找HTML元素的dataset属性。dataset 属性将数据属性存储为 JavaScript 对象。使用它,您的代码可以编写为:

document.querySelector('.sheet').addEventListener('scroll', function() {
  clearTimeout(this.dataset.scrollTimer);
  this.dataset.scrollTimer = setTimeout(function() {
    // do stuff
  }, 250);
)};