我希望遍历来自querySelectorAll的NodeList。
无效的代码
我得到的是这样的结果:
在 i=1 之后,输出就卡住了。对于第一个项目,“for”循环按预期运行,但是之后它就不再继续了。当我在浏览器控制台中运行 querySelectorAll 时,我能看到所有三个不同的项目。
这里我找到了一种行之有效的方法: 行之有效
产生以下输出:
我希望nodelist.length的值为3而不是0。
var nodelist = this.evaluate(function() {
return document.querySelectorAll('tr.firstrow');
});
this.echo("nodelist.length=" + nodelist.length);
for (var i=0; i<nodelist.length; i++) {
this.echo("i=" + i);
line = nodelist[i];
this.echo("Line: " + line.innerText);
}
我得到的是这样的结果:
nodelist.length=3
i=0
this it the first line
i=1
在 i=1 之后,输出就卡住了。对于第一个项目,“for”循环按预期运行,但是之后它就不再继续了。当我在浏览器控制台中运行 querySelectorAll 时,我能看到所有三个不同的项目。
这里我找到了一种行之有效的方法: 行之有效
var nodelist = this.evaluate(function() {
var nodes = document.querySelectorAll('tr.firstrow');
var array = [nodes[0].innerText,nodes[1].innerText,nodes[2].innerText];
return array;
});
this.echo("nodelist.length=" + nodelist.length);
for (var i=0; i<nodelist.length; i++) {
this.echo("i=" + i);
line = nodelist[i];
this.echo("Line: " + line);
}
但这很不方便。
然后我尝试将此节点列表转换为数组。但这种方法也不起作用,因为从 evaluate 函数返回的值丢失了。
不起作用
var nodelist=this.evaluate(function()
{
console.log("...evaluate()");
var fr_n=document.querySelectorAll('tr.firstrow');
console.log("fr_n.length:" + fr_n.length);
var fr_a=Array.prototype.slice.call(fr_n);
console.log("fr_a.length:" + fr_a.length);
console.log("typeof fr_a:" + typeof fr_a);
console.log("fr_a[0]=" + fr_a[0].innerText);
console.log("fr_a[1]=" + fr_a[1].innerText);
console.log("fr_a[2]=" + fr_a[2].innerText);
return fr_a;
});
this.echo("nodelist.length=" + nodelist.length);
if (Array.isArray(nodelist))
{
this.echo ("nodelist is array");
}
else
{
this.echo ("nodelist is not array");
}
for (var i=0; i<nodelist.length; i++)
{
this.echo("i:" + i);
line = nodelist[i];
this.echo("Line: " + line);
};
产生以下输出:
remote console.log: ...evaluate()
remote console.log: fr_n.length:3
remote console.log: fr_a.length:3
remote console.log: typeof fr_a:object
remote console.log: fr_a[0]=This is the first line I want to see
remote console.log: fr_a[1]=This is the second line I want to see
remote console.log: fr_a[1]=This is the third line I want to see
nodelist.length=0
nodelist is array
[info] [phantom] Done 4 steps in 6943ms
我希望nodelist.length的值为3而不是0。
line = nodelist[i];
。 - Sven Kirsten