[function] .apply()导致“预期的JScript对象" IE中的错误 [英] [function].apply() causing "JScript object expected" error in IE

查看:73
本文介绍了[function] .apply()导致“预期的JScript对象" IE中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码行导致IE中出现预期的JScript对象"错误:

The following line of code causes a "JScript object expected" error in IE:

hideElements.apply(window, elements);

根据IE,预期的JScript对象"指的是hideElements,该函数使用任意数量的HTML对象作为参数并将其隐藏.

According to IE, the 'expected JScript object' refers to hideElements, which is a function that takes any number of HTML objects as arguments and hide them.

具体地,我通过调用getElementsByTagName检索HTML对象数组,并且我希望将此数组作为函数hideElements的参数列表传递.在这种情况下,JS函数apply()正是我所需要的.我知道我肯定可以用不同的方式编写我的代码,但是由于它可以在Firefox和Chrome上完美运行,并且在技术上是正确的,所以我真的很想知道IE为什么会卡在那里.

Concretely, I retrieve an array of HTML objects via a call to getElementsByTagName, and I would like to pass this array as a list of arguments to the function hideElements. The JS function apply() is exactly what I need in that case. I know I could surely write my code differently, but since this works perfectly on Firefox and Chrome, and is technically correct, I'd really like to know why IE gets stuck there.

我确定在执行该行时:

  • window不是null且类型为Window;
  • elements不为null,且类型为HTMLCollection;和
  • hideElements是一个功能齐全的JS函数(可以完全正常工作,并且在执行上述代码时可以完全加载).
  • window is not null and of type Window;
  • elements is not null and of type HTMLCollection; and
  • hideElements is a fully functional JS function (that works perfectly on its own and that is fully loaded when the code above is executed).

推荐答案

getElementsByTagName返回nodeList. apply期望第二个参数为array.如果将elements转换为真实数组(使用循环),它应该可以工作.

getElementsByTagName returns a nodeList. apply expects the second argument to be an array. If you convert elements to a real array (using a loop), it should work.

注意:在IE< 9中,不可能使用Array.prototype.slice.call(elements),因此循环是创建数组的最安全方法,例如:

Note: In IE<9, it's not possible to use Array.prototype.slice.call(elements) for that, so a loop is the safest way to create an array, like:

function nodeList2Array(nodes){
  var arr = [];
  for (var i=1; i<nodes.length;(i+=1)){
    arr.push(nodes[i]);
  }
  return arr;
}

现在:hideElements.apply(window, nodeList2Array(elements));应该可以工作.

这篇关于[function] .apply()导致“预期的JScript对象" IE中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆