有什么方法可以在纯 javascript 中将元素作为函数获取吗?

Are there any ways to get an element as a function in pure javascript?

我很困惑,因为我注意到以下 2 个案例的结果与我预期的不一样;

console.log(typeof document.querySelector('.holder'));
console.log(typeof $('.holder'));

浏览器说这两种情况是相同的变量类型,object。但是当我尝试添加一个 .each 方法时,它说 document.querySelector('.holder') 不是函数。

    'use strict'
    const createMenuTable = (root, clips) => {
      return root.each(() => {
        console.log(root);
      })
    }
    let myTable = createMenuTable(
      document.querySelectorAll('.table'), 
      document.querySelector('.layerGroup')
    ); // When I change the `root` argument to the `$('.table')`, it runs w/o an error.
<div class="table">
  <div class="layerGroup">
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Uncaught TypeError: root.each is not a function

我的目标是像 jQuery 那样使用普通的 JavaScript 得到一个 element 作为函数,但不知道如何解决这个问题。

如果有人能向我解释为什么这 2 个案例即使变量类型相同也没有给出相同的结果,我将不胜感激。

用于此目的的 querySelectorAll method returns a NodeList which doesn't have any method like each but you can use NodeList#forEach 方法。

return root.forEach((ele) => {
   console.log(ele);
})


在 jQuery 中有 each() 方法只适用于 jQuery 对象,因此您可以通过 jQuery 包装集合来制定通用解决方案。

return $(root).each((i, ele) => {
   console.log(ele);
})