javascript本机等效于.each&。属性

javascript本机等效于.each&。属性,javascript,jquery,each,native,Javascript,Jquery,Each,Native,我正在尝试将以下jQuery脚本转换为本机javascript function isElementInViewport(el) { //special bonus for those using jQuery if (typeof jQuery === "function" && el instanceof jQuery) { el = el[0]; } var rect = el.getBoundingClientRect(); return (

我正在尝试将以下jQuery脚本转换为本机javascript

function isElementInViewport(el) {
  //special bonus for those using jQuery
  if (typeof jQuery === "function" && el instanceof jQuery) {
    el = el[0];
  }
  var rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
    rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
  );
}

$(document).on("scroll", function() {
  $(".anchor").each(function (idx, el) {
    if ( isElementInViewport(el) ) {
      if (window.history.pushState) {
        var urlHash = "#" + $(el).attr("id");
        window.history.pushState(null, null, urlHash);
      }
    }
  });
});
但是我得到了各种各样的控制台错误,说xxxxx不是函数等等。我想我没有正确地转换jQuery迭代(.each)&我也不知道如何转换$(el)和.attr

我希望将.attr更改为=>setAttribute这样简单,但事实并非如此


任何帮助都将不胜感激

非常接近-
forEach
的第一个参数是迭代的元素,而不是索引。(在jQuery中,参数是相反的——第一个参数是索引,第二个参数是项)

对于
.attr('id')
部分,您可以访问元素的普通
.id
属性:

document.addEventListener('scroll', function() {
  var anchor = document.querySelectorAll(".anchor");
  anchor.forEach(function(el) {
    if (isElementInViewport(el)) {
      if (window.history.pushState) {
        var urlHash = "#" + el.id;
        window.history.pushState(null, null, urlHash);
      }
    }
  });
});
还要注意,
querySelectorAll
返回一个
NodeList
NodeList.prototype.forEach
易于使用,但这是一项新功能,通常在2016年以前的浏览器中不受支持-为确保与旧浏览器的兼容性,请使用polyfill或调用
Array.prototype.forEach

document.addEventListener('scroll', function() {
  Array.prototype.forEach.call(
    document.querySelectorAll(".anchor"),
    function(el) {
      if (isElementInViewport(el) && window.history.pushState) {
        var urlHash = "#" + el.id;
        window.history.pushState(null, null, urlHash);
      }
    }
  );
});

function(idx,el)
应该是
function(el,idx)
$(el)。attr(“id”)
应该是
el.getAttribute(“id”)
,或者更好的
el.id
。非常感谢!!!stackoverflow告诉我我不能接受你的回答。哈哈,我不知道为什么。我一会儿就回来&试着再次接受它。希望它能起作用。(我不明白为什么这不是一个好答案。嗯…)stackoverflow现在允许我接受你的答案。我接受了。谢谢
document.addEventListener('scroll', function() {
  Array.prototype.forEach.call(
    document.querySelectorAll(".anchor"),
    function(el) {
      if (isElementInViewport(el) && window.history.pushState) {
        var urlHash = "#" + el.id;
        window.history.pushState(null, null, urlHash);
      }
    }
  );
});