我已将所有图片 url 存储在一个数组中,并正在尝试测试图片是否已正确加载。如果你看到下面的代码,我不得不一次又一次地重复几行代码。我怎样才能把它写成通用的?
casper.start()
var imagesArray = [];
imagesArray = ['https://www.google.co.in/images/srpr/logo11w.png',
'https://www.google.co.in/images/srpr/logo1w.png'];
casper.thenOpen(imagesArray[0], function () {
if (this.currentHTTPStatus === 404) {
this.warn(imagesArray[0] + ' is missing (HTTP 404)');
} else if (this.currentHTTPStatus === 500) {
this.warn(imagesArray[0] + ' is broken (HTTP 500)');
} else {
this.echo(' is okay (HTTP %s)');
}
});
casper.thenOpen(imagesArray[1], function () {
if (this.currentHTTPStatus === 404) {
this.warn(imagesArray[0] + ' is missing (HTTP 404)');
} else if (this.currentHTTPStatus === 500) {
this.warn(imagesArray[0] + ' is broken (HTTP 500)');
} else {
this.echo(' is okay (HTTP %s)');
}
});
casper.run(function() {
this.echo('Image loading test finished');
this.exit();
});
我尝试了下面的方法,调用了一个函数但是它抛出了解析器错误,我做错了什么,或者我该如何继续它?
function checkImages(item){
if (this.currentHTTPStatus === 404) {
this.warn(item + ' is missing (HTTP 404)');
} else if (this.currentHTTPStatus === 500) {
this.warn(item + ' is broken (HTTP 500)');
} else {
this.echo(' is okay (HTTP %s)');
}
}
casper.thenOpen(imagesArray[0], function () {
this.evaluate(checkImages(imagesArray[0]));
});
casper.thenOpen(imagesArray[1], function () {
this.evaluate(checkImages(imagesArray[1]));
});
提前致谢。
最佳答案
由于所有then*
函数都是异步步骤函数,将步骤插入队列,您可以在循环中调用它们。由于 imagesArray
是原生数组,因此可以使用 PhantomJS 支持的 Array.prototype.forEach
对其进行迭代:
var imagesArray = [
'https://www.google.co.in/images/srpr/logo11w.png',
'https://www.google.co.in/images/srpr/logo1w.png'
];
casper.start();
imagesArray.forEach(function(imageUrl){
casper.thenOpen(imageUrl, function () {
if (this.currentHTTPStatus === 404) {
this.warn(imageUrl + ' is missing (HTTP 404)');
} else if (this.currentHTTPStatus === 500) {
this.warn(imageUrl + ' is broken (HTTP 500)');
} else {
this.echo(' is okay (HTTP %s)');
}
});
});
casper.run();
一个简单的 for 循环就足够了,但是 thenOpen
中的 imagesArray[i]
会出现问题。 i
变量永远不会改变,因为每一步都是在循环完成后执行的。所以每个 imagesArray[i]
都会显示最后一个 url。因为 JavaScript 具有函数级范围,所以 url 绑定(bind)到每次迭代并且之后永远不会改变。
关于javascript - 如何将参数传递给casperjs中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20918831/