JSON - 如果语句故障排除

JSON - If Statement Troubleshooting

本文关键字:故障 排除 语句 如果 JSON      更新时间:2023-09-26

是什么导致 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。

你的问题出在你的遍历中。 $('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(..;
});

演示

$('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>');