2

这个脚本不适合我。

我知道问题出在.on('value')函数中,但我不知道它是什么。

这是我的脚本:

$(document).ready(function(){

//dynamic content switching inside the content section
function writeContent(page){
    //setting post to default error message
    var post = "Sorry, This page is undergoing maintenance.";
    //firebase data reference for the clicked link's content
    var dataRef = new Firebase("https://cityartist.firebaseio.com/"+page);
    //inserting the available content to the 'post' variable 
    dataRef.on("value",function(snapshot){
        if(snapshot.val() != null){
            post = snapshot.val();
            alert("post="+post);
        }   
    });
    //showing content in the content section and changing the page's title
    $("#content").append("<article class='post'><p>"+post+"</p></article>");
    $("title").text("CityArtist.org - "+page);
}

//switching pages using the navigation bar
$(".menu_link").click(function(){
    writeContent($(this).attr("name"));
});
 });
4

2 回答 2

2

Firebase 中的回调通常是异步触发的,因为 Firebase 必须等待数据到达。所以你的 on('value') 回调代码被调用 /after/ "//showing content in ..." 代码。你可以试试这个:

dataRef.on("value",function(snapshot){
    if(snapshot.val() != null){
        post = snapshot.val();
        alert("post="+post);
    }
    //showing content in the content section.
    $("#content").append("<article class='post'><p>"+post+"</p></article>");
});
于 2013-07-22T15:46:49.313 回答
0

您需要在回调中执行 DOM 更改(例如,在 Firebase 返回数据之后)。这是在上下文中:

$(document).ready(function(){

//dynamic content switching inside the content section
function writeContent(page){
    //setting post to default error message
    var post = "Sorry, This page is undergoing maintenance.";
    //firebase data reference for the clicked link's content
    var dataRef = new Firebase("https://cityartist.firebaseio.com/"+page);
    //inserting the available content to the 'post' variable 
    dataRef.on("value",function(snapshot){
        if(snapshot.val() != null){
            post = snapshot.val();
            alert("post="+post);
            //showing content in the content section and changing the page's title
            $("#content").append("<article class='post'><p>"+post+"</p></article>");
            $("title").text("CityArtist.org - "+page);
        }   
    });
}

//switching pages using the navigation bar
$(".menu_link").click(function(){
    writeContent($(this).attr("name"));
});
 });
于 2013-07-24T19:01:06.353 回答