Javascript数组与对象引用

时间:2015-01-27 12:06:54

标签: javascript arrays autoit

我遇到了一些障碍。当我直接返回getElementsByTagName,getElementsByClassName或querySelectorAll等对象引用并将它们返回给AutoIt时,我没有问题通过索引和使用返回的对象,但是如果我尝试通过数组将DOM中的对象引用存储到数组中push,我得到了正确的object.length,但数组为null。我认为这可能是一个局部变量问题,所以我全局存储了数据,但仍然遇到了同样的问题。

从下面的例子中,有没有办法返回对象引用,就好像我直接调用getElementsByTagName,getElementsByClassName或querySelectorAll,但只有我想要的项目?我担心我的javascript知识仍然缺乏。

//http://stackoverflow.com/a/25054465/4312966
//Thanks kapa
function IEExAutClassGetCollectionFunc() {
    var autDIV = document.createElement('div');
    autDIV.setAttribute('id', 'IEExAutClassGetCollectionId');
    document.body.appendChild(autDIV);
    var autVariable = document.getElementById("IEExAutClassGetCollectionId");
    autVariable.IEExAutClassGetCollection = function (oElm, sClass) {

        var sPattern, oElements, i, aresults = [];//, oRet;
        if (typeof sClass == 'undefined') {return 1;}
        oElm = (typeof oElm == 'undefined') ? document : oElm;

        /*  
        if (oElm.getElementsByClassName) { // IE8+
            oRet = oElm.getElementsByClassName(sClass);
            if (!oRet.length) {return 2;}
            return oRet
        }

        if (oElm.querySelectorAll) { // IE8+
            oRet = oElm.querySelectorAll("." + sClass);
            if (!oRet.length) {return 3;}
            return oRet
        }
        */

        // Pushing the array objects is not working
        // I get the object array back, but the objects are missing
        // object.length matches on both sides, here object.tagName matches
        // on the AutoIt side nothing in the .items(n)
        if (oElm.evaluate) { // IE6, IE7
            sPattern = ".//*[contains(concat(' ', @class, ' '), ' " + sClass + " ')]";
            oElements = oElm.evaluate(sPattern, oElm, null, 0, null);
            while ((i = oElements.iterateNext())) {
                aresults.push(i);
            }
        } else { // IE8
            oElements = oElm.getElementsByTagName("*");
            sPattern = new RegExp("(^|\\s)" + sClass + "(\\s|$)");
            for (i = 0; i < oElements.length; i++) {
                if ( sPattern.test(oElements[i].className) ) {
                    // this is the one I'm focused on
                    // I've tried creating a new object from the oElements object no luck
                    // I've tried adding the indexes manually (outside push) .item(n) no luck
                    // I've tried to aresults = oElements, fill results 0 - n, then use
                    //  aresults.length = length I want, and it doesn't trim like a standard
                    //  array.
                    aresults.push(oElements[i]);
                }
            }
        }
        if (!aresults.length) {return 4;}
        return aresults;
    };
}

0 个答案:

没有答案