将nodeList转换为数组(兼容性)

Posted CNundefined

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将nodeList转换为数组(兼容性)相关的知识,希望对你有一定的参考价值。

将nodeList转换为数组(兼容性)

function arrayofNodes(nodes){
    var arr = null;
    try{
        arr = Array.prototype.slice.call(nodes,0);
    }catch(ex){
        arr = new Array();
        for(var i=0,len=nodes.length; i < len; i++){
            arr.push(nodes[i]);
        }
    }
    return arr;
}

 

在IE8以前的浏览器中nodes非JScript对象而是COM对象,所以

Array.prototype.slice.call(nodes,0);

会出错

需要catch来捕获错误,然后手动创建数组

以上是关于将nodeList转换为数组(兼容性)的主要内容,如果未能解决你的问题,请参考以下文章