JSON - 如果声明故障排除

时间:2015-01-06 03:09:26

标签: javascript jquery json function if-statement

是什么导致if语句(totalViews === 0)无法正常运行?

该语句应该在“div.viewed”类中显示span标记。如果"totalViews"等于0(没有开始的跨度标记),则跨度的内部文本应显示为“0人已查看过您的帖子”。但是,一个span标签根本没有输入到"div.viewed"类。

其余的if语句似乎运作正常。

当前代码的示例:

function checkViewers() {
    $('div.viewed').each(function() {
        //Base Variables
        var viewer = $('span.user', this);
        var totalViews = viewer.length;
        var shortenViews = viewer.length -1;
        var viewerCount = $('span', this);

        if (totalViews === 0) {
            $('div.viewed', this).append('<span> 0 people have viewed your post.</span>');
        }
        if (totalViews == 1) {
            $('<span> has viewed your post.</span>').insertAfter(viewer.last());
        }
        if (totalViews == 2) {
            $('<span> and </span>').insertAfter(viewer.first());
            $('<span> have viewed your post.</span>').insertAfter(viewer.last());
        }
        if (totalViews >= 3) {
            $('<span> and </span>').insertAfter(viewer.first());
            $('<span class="user count"></span>').insertAfter(viewerCount.eq(1));
            $('.count', this).html(shortenViews + ' more people');
            $('<span> have viewed your post.</span>').insertAfter(viewer.last());
            viewer.slice(1).hide();
        }

    });
}

查看当前和完整的Plunker

2 个答案:

答案 0 :(得分:1)

你的问题在你的遍历中。 $('div.viewed', this)不存在。

使用$(selector,context)的上下文参数与编写相同:

$(this).find('div.viewed'); //look for descendant of "this"

变化:

$('div.viewed').each(function() {    
    /* "this" is an instance of div class= viewed*/

     /* look for a div WITHIN "this" with class=viewed"  --BUT  no such descendant*/
    $('div.viewed', this).append(..;    
});

$('div.viewed').each(function() { 
    /* I'm already here as "this" */   
    $(this).append(..;
});

DEMO

答案 1 :(得分:0)

$('div.viewed', this).append('<span> 0 people have viewed your post.</span>');

这里$('div.viewed',this)将返回一个空数组,

相反,你可能必须这样做

$('div.viewed').append('<span> 0 people have viewed your post.</span>');