2013-07-06 40 views
0

我正在使用.text()添加到div。我不知道我會加多少。但是如果我使用.text()多一次,它只會添加最後一個。我已經使用.text(msg1,msg2,msg3),這對我很有用,但如果文本更有序,我希望它。就像在每一個味精後都會有新的一行開始。我試圖添加空格,但這不起作用,並不是我想要的方式。我剛剛有一個div,我試圖添加,<p>的它,我試圖通過ID嘗試$("p:first")。我已經包括一個小提琴。添加到div的正確方法?

http://jsfiddle.net/G24aQ/12/

if(k1<10){ 
    msg1= "This will not space like a want." + " " 
    msg2= "I don know why not.  " 
    msg3= "How come.  " 
    $('#output1').text(msg1); 
    $('#p').text(msg2); 
    $('#output1').text(msg3+"  "+msg2+"  "+ msg1); 
} 

回答

2
  1. 您可以使用<br/>以新行添加消息。
  2. 您可以使用html而不是text並一次添加。要逐一添加,請一起使用htmlappend

演示:http://jsfiddle.net/G24aQ/14/

if (k1 < 10) { 
     msg1 = "This will not space like a want.<br/>"; 
     msg2 = "I don know why not.<br/>"; 
     msg3 = "How come.<br/>"; 
     $('#output1').html(msg3 + msg2 + msg1); //this will add all the three variables together into #output1 - replacing older content 
     /* 
     //To add one by one 
     $("#output1").html(msg3); // this will erase the older content so that you have a clean #output1 div 
     $("#output1").append(msg2); //this will add to the existing content, will not over write it 
     $("#output1").append(msg1); //this will add to the existing content, will not over write it 
     */ 
} 

始終牢記html() & text()會刪除選擇的一切,並添加新的內容進去。 append添加到現有內容。而且,如果使用text(),您的HTML標籤將被忽略。

html & append的文件瞭解更多信息。

+0

完美的作品,並很容易與追加加入!我會用你的例子,但我想知道你的答案和AntónioRegadas的答案之間有什麼區別。 – user2537145

1

您需要使用$(id).append (code);如果你想追加,而不是改變。

0

您應該使用append爲,如:

if (k1 < 10) { 
     msg1 = "This will not space like a want.<br/>"; 
     msg2 = "I don know why not.<br/>"; 
     msg3 = "How come.<br/>"; 
     $('#output1').append('<p>'+msg1+'</p>'+'<p>'+msg2+'</p>'+'<p>'+msg3+'</p>'); 
} 

,並使用HTML標記一樣<p>,使他們出現在新的生產線。

你也可以這樣來做:

if (k1 < 10) { 
    msg1 = "This will not space like a want.<br/>"; 
    msg2 = "I don know why not.<br/>"; 
    msg3 = "How come.<br/>"; 
    var e = $('<p>'+msg1+'</p>'+'<p>'+msg2+'</p>'+'<p>'+msg3+'</p>'); 
    $('#output1').append(e); 
} 
1

至於我記得,HTML只會渲染過度的空間爲一體。 你必須使用

&nbsp; 

或者把每個文本span標記內與右邊距

<span style="margin-right:10px"></span> 
相關問題