如果在内部循环

时间:2015-02-16 10:23:06

标签: javascript jquery node.js

我在这里搞砸了,请帮忙。

我正在抓取一个网站。

.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部分根本不执行。

我做错了什么?

2 个答案:

答案 0 :(得分:5)

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

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

}

您也可以尝试(未测试)

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

此外,如果只有1个元素具有类MyElement,那么

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

答案 1 :(得分:1)

在我看来,您希望将其缓存在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');
      }
    });
相关问题