gpt4 book ai didi

javascript - JSON - If 语句故障排除

转载 作者:行者123 更新时间:2023-12-03 11:07:09 28 4
gpt4 key购买 nike

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

该语句应该在“div.viewed”类中显示一个span标签。如果 "totalViews" 等于 0(开始时没有 Span 标签),Span 的内部文本应为“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(..;
});

DEMO

关于javascript - JSON - If 语句故障排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791516/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com