【问题标题】:JSON - If Statement TroubleshootingJSON - If 语句故障排除
【发布时间】:2015-01-06 03:09:25
【问题描述】:

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

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

其余的 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').each(function() {...});,你希望$('div.viewed', this).append(...);在里面插入一些东西,如果DOM是这样构造的,但$(this).append(...);似乎更合适。

标签: javascript jquery json function if-statement


【解决方案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

【讨论】:

    【解决方案2】:
    $('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>');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 2013-07-15
      • 2010-11-30
      • 2021-09-11
      • 2012-02-18
      相关资源
      最近更新 更多