代码之家  ›  专栏  ›  技术社区  ›  Amma

Safari和IE中的Javascript ES6 TypeError

  •  2
  • Amma  · 技术社区  · 8 年前

    我正在使用另一个在Wordpress网站上使用ES6的人编写的Javascript代码。它调用Ajax以在DOM中显示数据,DOM适用于Chrome和Firefox,但由于某些原因,Safari在控制台中出现以下错误:

    TypeError: document.querySelectorAll(".js_zip-lookup__submit").forEach is not a function. (In 'document.querySelectorAll(".js_zip-lookup__submit").forEach(function(e){e.addEventListener("click",function(){displayResults(e.parentNode.querySelector(".zip-lookup__input").value)})})', 'document.querySelectorAll(".js_zip-lookup__submit").forEach' is undefined)
    

    function finderInit(){
      document.querySelectorAll('.js_zip-lookup__submit').forEach(function(button){
        button.addEventListener('click', function(){
          const zip = button.parentNode.querySelector('.zip-lookup__input').value;
          displayResults(zip);
        });
      });
    
      document.querySelectorAll('.zip-lookup').forEach(function(form){
        form.addEventListener('submit', function(e){
          e.preventDefault();
          const zip = form.querySelector('.zip-lookup__input').value;
          displayResults(zip);
        })
      });
    }
    

    3 回复  |  直到 8 年前
        1
  •  2
  •   Estus Flask    8 年前

    document.querySelectorAll 退货 NodeList 对象,而不是数组。按原样 can be seen on MDN 节点列表 forEach 方法,但它并没有得到很好的支持,这就是为什么它在最近的Firefox和Chrome中有效,但在其他浏览器(Safari)中无效的原因:

    要以兼容的方式迭代节点列表和其他迭代器, Array.from

    Array.from(document.querySelectorAll(".js_zip-lookup__submit")).forEach(...);
    
        2
  •  2
  •   Amma    8 年前

    我尝试了许多阵列的变体。原型,但唯一解决IE&Safari兼容性问题包括下面的polypill片段,解决方案见 this blog :

    (function () {
        if ( typeof NodeList.prototype.forEach === "function" ) return false;
        NodeList.prototype.forEach = Array.prototype.forEach;
    })();
    
        3
  •  1
  •   traktor    8 年前

    正如@Estus所提到的,旧版本的Safari没有实现 .forEach Array.prototype.forEach 在中定义为泛型 ES5.1

    forEach函数是有意泛型的;它不要求其此值是数组对象。因此,它可以作为一种方法转移到其他类型的对象。forEach函数能否成功应用于主机对象取决于实现。

    大堆原型forEach公司 并将要执行的函数传递给它。作为一个精简(廉价)的测试用例:

    var col = document.getElementsByTagName("p");
    //col.forEach(                    function (el) {document.write(el.id)});
    Array.prototype.forEach.call(col, function (el) {document.write(el.id)});
    <p id="p1"></p>
    <p id="p2"></p>
    <p id="p3"></p>
    <p id="p4"></p>

    推荐文章