[function] .apply()导致“预期的JScript对象" IE中的错误 [英] [function].apply() causing "JScript object expected" error in 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 typeWindow
;elements
is not null and of typeHTMLCollection
; andhideElements
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屋!