2015-01-04 141 views
0

如何获取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'); 
    } 

} 

的函数叫做朝向剩余JS的底部,JSON数据之后被调用。

理想情况下,JSON数据应该输入到HTML中,并且该函数应该能够捕获观众的数量。这应该影响观看者在HTML中的显示方式,以及列出的观众人数。

查看Plunker

+0

在上面的代码中,你不显示如何调用它。 – epascarello

+0

并查看该随机站点上的代码后。 Ajax是异步的。你从互联网上下了一个比萨饼,你试图在比萨到达你的房子之前吃。你必须等到披萨出现后再吃。也就是说,只有数据在那里,你才能调用你的函数。所以当你设置html时,你可以调用你的函数。 – epascarello

+0

@epascarello我喜欢你可视化异步的新方式 – charlietfl

回答

4

使我的评论答案:

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!!!! 
+0

我打开了plunkr ...测试了这个! Works ... – rfornal

+0

@epascarello您的比喻对于可视化Ajax非常有帮助。如果我发布示例,我通常使用JSFiddle。我使用Plunker的原因纯粹是因为我想在外部和内部链接JSON。感谢您的帮助! – Andrew