我试图将jQuery的Sizzle选择器引擎用作自定义Selenium locate 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的片段:
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;
};
它解决了这个奇怪的问题。
为什么这个修复工作有任何想法?!
答案 0 :(得分: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;
};
}