JSON - If 语句故障排除

JSON - If Statement Troubleshooting

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

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

其余的 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

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

此处 $('div.viewed', this) 将 return 一个空数组,

相反,您可能必须像

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

你的问题出在你的遍历上。 $('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