JSON - 如果语句故障排除
JSON - If Statement Troubleshooting
是什么导致 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>');
相关文章:
- JS条件故障排除
- Django无法通过urls.py配置找到djangular/app.js文件.如何进行故障排除
- 对 Drupal 站点的客户端 JS 问题进行故障排除
- iMacros机架名称故障排除
- jQuery输入值故障排除
- JavaScript数学&警报故障排除
- 对 AJAX XMLHTTP 对象创建进行故障排除
- 附加 JSON 对象编号 - 故障排除
- JSON - 如果语句故障排除
- 基本调用函数故障排除
- 对使用 iframe 的简单 jquery 展开/折叠进行故障排除
- 对简单的 JavaScript 幻灯片进行故障排除
- Dygraph 对 CSV 进行故障排除
- 对无限循环错误进行故障排除
- 使用 JS 进行故障排除
- jQuery .hover 函数故障排除
- 如何对以下 js 索引脚本进行故障排除
- 对 jQuery 切换进行故障排除
- 对 Stripe 的 JavaScript 进行故障排除
- 替换c#函数bijJquery在不知道如何进行故障排除的情况下不起作用