2012-03-14 8 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]+ "%"); 

    } 

をこれは明らかに動作しません。第2のメッセージは、第1のメッセージのテキストを上書きする。両方のメッセージを表示する適切な方法は何ですか。

答えて

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()方法がセレクタにあるものをすべて置き換えられます....私はあなたが交換しないで追加する必要があり、既存のHTML

0

の最後に追加されますappend()をしたいと思います表示要素の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]+ "%"); 
関連する問題