2013-01-02 29 views
1

我不知道如何在Stackoverflow中搜索這個問題,它給出了不同的解決方案,並且不涉及我的問題。所以我會再次需要你的幫助。可變obj的

值:

item.title = Title1 and Title2 

item.description = Description1 and Description2 

HTML文件:

function test_pop() { 
    var fb_id = "xxxxxxxxxxxx"; 
    var v_id = "xxxxxxxx"; 

    $.post('http://mysite.com/myfile.php', {fb_id: fb_id, v_id: v_id}, function(data) { 
     var obj = $.parseJSON(data); 
     $.each(obj,function(index, item){ 
      achievement = "You Obtained " + item.title + " " + item.description; 
      achievement_pop(achievement); 
     }); 
    }); 
} 

achievement_pop功能:

function achievement_pop(data) { 
    $("#achievement_popup").html(data).show(); //DIV that should show up 
} 

所以,問題是,當DIV顯示出來,它只輸出:

<div> <!-- Imagine that this content is inside a DIV --> 
**You Obtained Title2 Description2** 

    </div> 

但我的願望輸出爲:

<div> <!-- Imagine that this content is inside a DIV --> 

**You Obtained Title1 Description1** 

**You Obtained Title2 Description2** 

    </div> 

希望你們幫幫我,謝謝。

回答

3

html函數正在替換整個div的內容,它不僅僅是添加。

一個解決辦法是用

$("#achievement_popup").html($("#achievement_popup").html()+data).show(); 

更換

$("#achievement_popup").html(data).show(); 

但它是一個有點沉重。就個人而言,我會首先構建html並使用html函數只有一次。

+0

它工作正常!感謝您的回答,我很感激! :) –

2

使用append()添加結束元素,而不是與html()

完全替代的內容,或者要替換現有的內容與所有的新內容在一次:

/* start with empty string*/ 
var achievement=''; 
$.each(obj,function(index, item){ 
    /* add to string on each pass of loop - can use any html you want here*/ 
    achievement += "You Obtained " + item.title + " " + item.description +'<br>'; 
}); 
/* update element once all data parsed*/ 
achievement_pop(achievement); 

解析到字符串和進行一次更新是從處理角度來看效率最高的

+0

謝謝,它也工作。 :) –