var casper = require('casper').create({
logLevel:'debug',
verbose:true
});
casper.start('http://pcdtattoo.en.alibaba.com/productlist.html',function getItems(){
var products = this.evaluate(function(){
var $ = jQuery;
var c = $('.app-productsGalleryView li');
var items = [];
c.each(function(){
var product = {};
product.title = $(this).find('.product-title>a').text().trim();
product.link = $(this).find('.product-title>a').attr('href');
product.img = $(this).find('img').attr('src');
items.push(product);
})
return items;
})
this.echo("test:"+ Array.isArray(products)); //works
products.forEach(function(item,i){
this.echo('Test:' + i); //not working
})
}
我通常使用 this.echo
将调试信息显示到输出中。在上面的代码中,第一个 this.echo
调用起作用,并将输出 test:true
以及其他调试信息。第二个不起作用并且没有输出任何内容,这是怎么回事?
最佳答案
在您的情况下,this
指的是window.object
,并且可能不是您所期望的。 native forEach
接受第二个参数 (arr.forEach(callback[, thisArg])
),它允许您传递上下文。
示例
[1,2,3].forEach(function () {
console.log(this); // this refers to window
});
// output
[object DOMWindow]
[object DOMWindow]
[object DOMWindow]
[1,2,3].forEach(function () {
console.log(this); // this refers to caspar
}, this);
// output
[object Casper], currently at https://localhost/de/register
[object Casper], currently at https://localhost/de/register
[object Casper], currently at https://localhost/de/register
提示: It's always good to know your API 。 ;)
关于javascript - casperjs:显示调试信息输出的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38086545/