jQuery returns 正确的元素数量,但只有第一个是对象
jQuery returns correct number of elements, but only the first is an object
我正在创建一个 casperjs
脚本来解析网页中的数据。我正在使用 jQuery 和 casperjs
。
我遇到的问题是,当我尝试遍历 article
个元素时,除第一个元素外,每个元素都是 null
。该脚本报告页面上正确的元素数量。
我的代码如下(我删除了部分脚本,因为它不是必需的)。
var articles = null;
/*
* Parse all article elements
*/
casper.then(function() {
console.log('Parsing articles from feed ...');
articles = this.evaluate(function() {
return $('article');
});
console.log(typeof(articles)); // prints 'object'
// Prints 56
console.log(articles.length);
});
/*
* Parse data from article elements
*/
casper.then(function() {
for(i=0; i<=articles.length; i++)
{
console.log(articles[i]);
}
});
当我 运行 脚本时,我从 for
循环中得到以下内容:
[object Object]
null
null
null
null
null
null
...
知道为什么会这样吗?
返回的 jQuery 集合,在本例中 $('article')
,不是 数组。您需要使用 .each() 函数对其进行迭代。 注意,这与 $.each() 函数不同。
有关如何遍历 jQuery 个集合的详细信息,请参阅 this article。
阅读 jQuery object 本身:
When creating new elements (or selecting existing ones), jQuery returns the elements in a collection. Many developers new to jQuery assume that this collection is an array. It has a zero-indexed sequence of DOM elements, some familiar array functions, and a .length property, after all. Actually, the jQuery object is more complicated than that.
我正在创建一个 casperjs
脚本来解析网页中的数据。我正在使用 jQuery 和 casperjs
。
我遇到的问题是,当我尝试遍历 article
个元素时,除第一个元素外,每个元素都是 null
。该脚本报告页面上正确的元素数量。
我的代码如下(我删除了部分脚本,因为它不是必需的)。
var articles = null;
/*
* Parse all article elements
*/
casper.then(function() {
console.log('Parsing articles from feed ...');
articles = this.evaluate(function() {
return $('article');
});
console.log(typeof(articles)); // prints 'object'
// Prints 56
console.log(articles.length);
});
/*
* Parse data from article elements
*/
casper.then(function() {
for(i=0; i<=articles.length; i++)
{
console.log(articles[i]);
}
});
当我 运行 脚本时,我从 for
循环中得到以下内容:
[object Object]
null
null
null
null
null
null
...
知道为什么会这样吗?
返回的 jQuery 集合,在本例中 $('article')
,不是 数组。您需要使用 .each() 函数对其进行迭代。 注意,这与 $.each() 函数不同。
有关如何遍历 jQuery 个集合的详细信息,请参阅 this article。
阅读 jQuery object 本身:
When creating new elements (or selecting existing ones), jQuery returns the elements in a collection. Many developers new to jQuery assume that this collection is an array. It has a zero-indexed sequence of DOM elements, some familiar array functions, and a .length property, after all. Actually, the jQuery object is more complicated than that.