2012-03-14 71 views
1

我正在使用以下函數打印出javascript變量的內容。如何使用jQuery正確打印HTML中的變量

function message(){ 
     $("#description").html("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%"); 

    } 

這正確正常工作,但是如果我試試這個:

function message(){ 
    $("#description").html("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%"); 
    $("#description").html("Candidate " + (lowest2+1) + " was the second to get eliminated ending on " + results[lowest2][0]+ "%"); 

    } 

這顯然是行不通的。第二條消息覆蓋第一條消息的文本。什麼是正確的方式顯示這兩個消息。

回答

4
function message(){ 
    var output; 
    output = "Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%"; 
    output += "Candidate " + (lowest2+1) + " was the second to get eliminated ending on " + results[lowest2][0]+ "%"; 
    $("#description").html(output); 

    } 

保持DOM操作儘可能少的性能的緣故(它會爲你節省不必要的頁面重新繪製):只使用一個變量包含您的所有字符串,並做插入一次,所以要避免多重昂貴調用jQuery函數。

1

使用.append()

function message(){ 
    $("#description").append("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%"); 
    $("#description").append("Candidate " + (lowest2+1) + " was the second to get eliminated ending on " + results[lowest2][0]+ "%"); 

    } 
0

html()方法將取代所有的都選擇....我想你想append()這更增加了結束現有的HTML

0

您需要添加的,而不是取代顯示元素的html。

因此,像這樣:

$("#description").append("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%" + "<br />"); 

.append()可以採取一個jQuery對象,原生DOM元素,或者普通的HTML字符串。

根據您的實際數據是如何結構化的,更強大的方法是建立一個DOM片斷,然後它添加到容器:

function message(){ 
    $('<div class="result">').html(_your_message_here_).appendTo('#description'); 
    $('<div class="result">').html(_next_message_here_).appendTo('#description'); 
} 

然後,你可以根據需要樣式div.result,不用擔心換行等

1

使用

$("#description").html("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%"); 
    $("#description").append("Candidate " + (lowest2+1) + " was the second to get eliminated ending on " + results[lowest2][0]+ "%");