如何让函数checkViewers()正常工作?我相信我在JS文档文件中称它为错误,因此JS无法正确读取该函数。
当前代码:
//Content Viewer Information
function checkViewers() {
//Base Variables
var viewer = $('#viewed span.user');
var totalViews = $('#viewed span.user').length;
var shortenViews = $('#viewed span.user').length -1;
if (totalViews === 0) {
$('<span> 0 people have </span>').insertBefore($('#viewed span:last-child'));
}
if (totalViews === 2) {
$('<span> and </span>').insertAfter(viewer.first());
}
if (totalViews >= 3) {
viewer.slice(1).hide();
$('<span> and </span>').insertAfter(viewer.first());
$('<span class="user count"></span>').insertAfter(viewer.eq(2));
$('.count').html(shortenViews + ' more people');
}
}
在调用 JSON 数据后,将在其余 JS 的底部调用该函数。
理想情况下,JSON 数据应输入到 HTML 中,并且函数应捕获查看者的数量。然后,这应该会影响查看器在 HTML 中的显示方式,以及列出的查看器数量。
查看普伦克。
让我的评论成为答案:
Ajax 是异步的。你从互联网上订购了一个披萨,你试图在披萨到达你家之前吃掉它。你必须等披萨出现才能吃。AKA,在数据存在之前,您无法调用函数。所以当你设置 html 时,你调用你的函数
xhr.onload = function() { //<--Function is called when the Pizza shows up at your door and the doorbell rings
... //removed a bunch of code....
//Update Page With New Content
var viewerSection = $('#viewed');
viewerSection.html(newViewers); //You open up the pizza box
checkViewers(); //<--- MOVE IT HERE, The pizza is here!!!!
}
};
xhr.open('GET', 'data.json', true); //<-- You set up your pizza order
xhr.send(null); //<--You make the pizza purchase
//checkViewers(); <-- PIZZA IS NOT HERE!!!!