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
以及其他调试信息。第二个不起作用,什么都不输出,它有什么问题?
答案 0 :(得分:1)
在您的情况下,this
指的是window.object
,可能不是您所期望的。原生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