0

我正在使用.text()添加到div. 不知道要加多少。但是,如果我使用.text()更多,那么它只会添加最后一个。我用过.text(msg1,msg2,msg3),这对我有用,但如果文本更有序,我会喜欢它。就像在每个味精之后都会开始一个新行。我试图添加空格,但这不起作用,也不是我想要的方式。我刚刚有一个 div,我尝试添加,<p>'s,我$("p:first")尝试通过 ID 尝试。我已经包括了一个小提琴。

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);
}
4

4 回答 4

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添加到现有内容。而且,如果使用了您的 HTML 标签,将被忽略text()

html更多信息的文档append

于 2013-07-06T21:10:10.980 回答
1

$(id).append (code);如果要附加,则需要使用,而不是更改。

于 2013-07-06T21:06:24.737 回答
1

据我记得,html 只会将过多的空格渲染为一个。你必须使用

 &nbsp;

或将每个文本放在具有右边距的 span 标签内

<span style="margin-right:10px"></span>
于 2013-07-06T21:36:03.833 回答
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);
}
于 2013-07-06T21:26:57.830 回答