本文介绍了如何在JavaScript中检测HTMLCollection / NodeList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不确定我当前的实现是否始终可用:
I'm not sure my current implementation is available all the time:
function isNodeList(nodes) {
var result = Object.prototype.toString.call(nodes);
// modern browser such as IE9 / firefox / chrome etc.
if (result === '[object HTMLCollection]' || result === '[object NodeList]') {
return true;
}
//ie 6/7/8
if (typeof(nodes) != 'object') {
return false;
}
// detect length and item
if (!('length' in nodes) || !('item' in nodes)) {
return false;
}
// use the trick NodeList(index),all browsers support
try {
if (nodes(0) === null || (nodes(0) && nodes(0).tagName)) return true;
}
catch (e) {
return false;
}
return false;
}
常见的情况是{length:1,item:function(){return [];}}
chrome / safari / opera中的结果值是'[object NodeList]'。
$
在firefox和IE 9中,它是'[object HTMLCollection]'。
A common situation is {length:1,item:function(){return [];}}
The value of result in chrome / safari / opera is '[object NodeList]'.
In firefox and IE 9 , it is '[object HTMLCollection]'.
哪个是标准值?
推荐答案
如果节点类型 NodeList
NodeList.prototype.isPrototypeOf(nodes)
@DavidSpector, HTMLCollection 你可以类似地使用:
@DavidSpector, for HTMLCollection you can similarly use :
HTMLCollection.prototype.isPrototypeOf(collection)
这篇关于如何在JavaScript中检测HTMLCollection / NodeList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!