我不确定我当前的实现是否一直可用:
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中result的值是'object NodeList‘。
在firefox和IE9中,它是'object HTMLCollection‘。
哪个是标准值?
发布于 2011-08-30 11:22:35
我会以不同的方式构建代码:
function isNodeList(nodes) {
var stringRepr = Object.prototype.toString.call(nodes);
return typeof nodes === 'object' &&
/^\[object (HTMLCollection|NodeList|Object)\]$/.test(stringRepr) &&
(typeof nodes.length === 'number') &&
(nodes.length === 0 || (typeof nodes[0] === "object" && nodes[0].nodeType > 0));
}备注:
使用较少的返回路径使代码更易于阅读,并坚持一种类型的逻辑,如果可能的话(即,在nodeList
hasOwnProperty()而不是checks)
"item"方括号来索引列表
&&链添加更多检查发布于 2014-04-23 23:23:22
脚本
Element.prototype.isNodeList = function() {return false;}
NodeList.prototype.isNodeList = HTMLCollection.prototype.isNodeList = function(){return true;}像这样使用
var d; // HTMLCollection|NodeList|Element
if(d.isNodeList()){
/*
it is HTMLCollection or NodeList
write your code here
*/
}else{
/*
it is not HTMLCollection and NodeList
write your code here
*/
}发布于 2016-10-11 03:56:45
下面是如何在现代浏览器中测试对象是否为NodeList:
if (nodes instanceof NodeList) {
// It's a NodeList object
}https://stackoverflow.com/questions/7238177
复制相似问题