【问题标题】:Strange behavior when applying Array.prototype.slice method to result of querySelectorAll将 Array.prototype.slice 方法应用于 querySelectorAll 的结果时的奇怪行为
【发布时间】:2011-04-12 20:02:15
【问题描述】:

我正在尝试使用 jQuery 的 Sizzle 选择器引擎作为自定义 Selenium 定位 API,如本文所示:http://johnjianfang.blogspot.com/2009/04/how-to-use-jquery-to-create-custom.html

不幸的是,当我使用selenium.click('jquery=a.mylink') 时,什么都没有发生。

selenium.click('css=a.mylink') 完美运行。

我做了一些研究,发现问题在于 jQuery 如何转换 querySelectorAll API 的结果。这是 jQuery 1.4.2 中的 sn-p:

Sizzle = function(query, context, extra, seed){
    context = context || document;

    // Only use querySelectorAll on non-XML documents
    // (ID selectors don't work in non-HTML documents)
    if ( !seed && context.nodeType === 9 && !isXML(context) ) {
        try {
            return makeArray( context.querySelectorAll(query), extra );
        } catch(e){}
    }

    return oldSizzle(query, context, extra, seed);
};


var makeArray = function(array, results) {
    array = Array.prototype.slice.call( array, 0 );

    if ( results ) {
        results.push.apply( results, array );
        return results;
    }

    return array;
};

当我像这样更改makeArray 时:

var makeArray = function(arrayLikeObject, results) {

    var array = new Array(arrayLikeObject.length);
    for (var i = 0, n = arrayLikeObject.length; i < n; i++) {
        array[i] = arrayLikeObject[i];
    }

    if ( results ) {
        results.push.apply( results, array );
        return results;
    }

    return array;
};

它解决了这个奇怪的问题。

任何想法为什么这个修复有效??!

【问题讨论】:

  • arrayA[0] === arrayB[0] 呢?
  • true,即使对于 (var p in arrayA[0]) { if(arrayA[0][p] !== arrayB[0][p]) { alert('diff'); } } 从不提醒 :)
  • 你在哪些浏览器中测试过这个?
  • 你修复了 jQuery。恭喜。

标签: javascript dom selenium-rc css-selectors jquery-1.4


【解决方案1】:

浏览器可能无法使用内置方法将 nodeList 转换为数组。您的后备方案几乎与jQuery 1.4.2 source 中包含的后备方案完全相同:

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
    Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;

// Provide a fallback method if it does not work
} catch(e){
    makeArray = function(array, results) {
        var ret = results || [];

        if ( toString.call(array) === "[object Array]" ) {
            Array.prototype.push.apply( ret, array );
        } else {
            if ( typeof array.length === "number" ) {
                for ( var i = 0, l = array.length; i < l; i++ ) {
                    ret.push( array[i] );
                }
            } else {
                for ( var i = 0; array[i]; i++ ) {
                    ret.push( array[i] );
                }
            }
        }

        return ret;
    };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-18
    • 2016-06-24
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    相关资源
    最近更新 更多