如何使函数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中显示查看器的方式,取决于列出了多少查看器。
查看柱塞。
发布于 2015-01-04 03:27:29
我的评论是:
Ajax是异步的。你在网上订了一个比萨饼,你试着在它到达你的房子之前吃它。你得等比萨饼出现才能吃。也就是说,在数据存在之前你不能调用你的函数。因此,当您设置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!!!!https://stackoverflow.com/questions/27762015
复制相似问题