如何使用jQuery在HTML中正确打印变量

时间:2012-03-14 16:55:08

标签: javascript jquery html

我使用以下函数打印出javascript变量的内容。

  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]+ "%");

  }

这显然不起作用。第二条消息将覆盖第一条消息的文本。显示两条消息的正确方法是什么。

5 个答案:

答案 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操作(它将使您免于不必要的页面重新绘制):只需使用一个变量来包含所有字符串并执行一次插入,以避免多次拨打{{{ 1}}功能。

答案 1 :(得分: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]+ "%");

  }

答案 2 :(得分: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]+ "%");

答案 3 :(得分:0)

html()方法将替换选择器中的所有内容....我认为您希望append()添加到现有html的结尾

答案 4 :(得分: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样式,而不用担心换行符等。