基本呼叫功能故障排除
Basic Calling Function Troubleshooting
如何获取函数 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 中的显示方式,取决于列出的观众数量。
查看 Plunker.
将我的评论作为答案:
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!!!!
如何获取函数 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 中的显示方式,取决于列出的观众数量。
查看 Plunker.
将我的评论作为答案:
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!!!!