如果其他内循环

我在这里打破了我的头,请帮忙。

我正在抓取一个网站。

.MyElement容器包含我试图获取的gif或jpg源url。

我在我的node.js应用程序中使用基于Cheerio的.each循环。

$('.MyElement').each(function(i, element){ if ($(this).find($('.animation'))) { resourceLinks = $(this).find($('.animation')).attr('src'); //if there is an .animation class element, get the gif from it } else { resourceLinks = $(this).find($('img')).attr('src'); //in all other cases, just fetch regular jpg }; }); 

第一部分(IF)执行正常,但ELSE部分根本不执行。

我究竟做错了什么?

.find()总是返回一个jQuery对象,所以它总是会是真的,如果你想检查是否有一个类animation的元素,然后检查返回的jQuery对象的长度

 if ($(this).find('.animation').length) { 

}

你也可以尝试(没有testing)

 $('.MyElement').each(function (i, element) { resourceLinks = $(this).find('.animation, img').attr('src'); }); 

另外,如果只有一个MyElement类的元素,那么

 resourceLinks = $('.MyElement').find('.animation, img').attr('src'); 

在我看来你想caching在var:

  resourceLinks = $('.MyElement').find('.animation').attr('src') || $('.MyElement').find('img').attr('src'); 

而不是使用jQuery对象尝试查找类名称:

  $('.MyElement').each(function(i, element) { if ($(this).find('.animation').length) { resourceLinks = $(this).find('.animation').attr('src'); } else { resourceLinks = $(this).find('img').attr('src'); } });