gpt4 book ai didi

javascript - While 循环设置 CasperJS "then()"步骤

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:00:57 25 4
gpt4 key购买 nike

我正在尝试测试一些按钮的视觉状态——悬停、单击、聚焦——并且正在寻找一种方法来不复制基本相同的 casper.then()一遍又一遍地命令。我认为我应该能够在一个简单的循环中执行此操作。

我制作了一个由(当前)5 个按钮组成的小阵列,并循环遍历它们,为我想要记录的每个状态添加 CasperJS 步骤。不幸的是,实际上只执行了最后一个步骤。

我读过很多关于循环的帖子,但它们似乎都涉及点击页面上的链接或其他一些似乎与我正在寻找的内容不符的场景。

也许我只是太笨了?下面的代码...

casper.thenOpen( 'docs/buttons/test.html' );

var buttonStyles = [
{ selector: '.grey0', title: 'Button - Grey 0' },
{ selector: '.grey25', title: 'Button - Grey 25' },
{ selector: '.grey50', title: 'Button - Grey 50' },
{ selector: '.grey75', title: 'Button - Grey 75' },
{ selector: '.grey100', title: 'Button - Grey 100' },
];

while (buttonStyles.length > 0) {

buttonStyle = buttonStyles.pop();

casper.then(function(){
phantomcss.screenshot(buttonStyle.selector, buttonStyle.title);
});

casper.then(function(){
this.mouse.move(buttonStyle.selector);
phantomcss.screenshot(buttonStyle.selector, buttonStyle.title + ' - Hover');
});

casper.then(function(){
this.mouse.down(buttonStyle.selector);
phantomcss.screenshot(buttonStyle.selector, buttonStyle.title + ' - Down');
});
}

casper.test.done();

最佳答案

问题是 buttonStyle 是一个全局变量。当您遍历 buttonStyles 数组时,所有 5 * 3 = 15 个 then block 都会被安排,但是由于 buttonStyle 在每个 then 仅阻止最后一个 buttonStyle 实际上检查了 5 次。

Javascript 没有 block 级作用域(while 内部),只有函数级作用域。解决方案是引入一个函数来执行此操作。您可以使用 IIFE 或 casper.repeat,例如 you did .

while (buttonStyles.length > 0) {
buttonStyle = buttonStyles.pop();
(function(buttonStyle){
casper.then(function(){
phantomcss.screenshot(buttonStyle.selector, buttonStyle.title);
});

casper.then(function(){
this.mouse.move(buttonStyle.selector);
phantomcss.screenshot(buttonStyle.selector, buttonStyle.title + ' - Hover');
});

casper.then(function(){
this.mouse.down(buttonStyle.selector);
phantomcss.screenshot(buttonStyle.selector, buttonStyle.title + ' - Down');
});
})(buttonStyle);
}

关于javascript - While 循环设置 CasperJS "then()"步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25597356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com