为什么JQuery和Javascript DOM方法会删除空白?

时间:2016-08-31 21:18:01

标签: javascript jquery dom

我试图在Javascript中写一个聊天室。好像您在消息提交框中发送了h e l l o,它会在消息日志中将h e l l o放在每个人的消息日志中。我也尝试使用原生DOM方法,同样的事情也发生在那里。

将消息放入日志的Javascript是这样的:

socket.on('chat message', function(msg){
        $('#messages').append($('<li style="background: #ffffff;">' + msg + '</li>'))
})

放置位置的HTML是这样的:

<ul id="messages">
</ul>

有人可以告诉我为什么会发生这种情况,以及如何防止这种情况发生。

2 个答案:

答案 0 :(得分:3)

浏览器在显示文本时不会显示破碎的空白,您可以使用CSS更改它

=IMPORTRANGE(M4, CONCATENATE(INDIRECT(Z1), "!$F$2"))

有效值如下

#messages li {
  white-space: pre;
}

&#13;
&#13;
Value    |  Description
_________|_________________________________________________________________________
normal   |  Sequences of whitespace will collapse into a single whitespace. 
         |  Text will wrap when necessary. This is default.
_________|_________________________________________________________________________
nowrap   |  Sequences of whitespace will collapse into a single whitespace. 
         |  Text will never wrap to the next line. 
         |  The text continues on the same line until a <br> tag is encountered.
_________|_________________________________________________________________________
pre      |  Whitespace is preserved by the browser. 
         |  Text will only wrap on line breaks.  
         |  Acts like the <pre> tag in HTML.
_________|_________________________________________________________________________
pre-line |  Sequences of whitespace will collapse into a single whitespace.
         |  Text will wrap when necessary, and on line breaks.
_________|_________________________________________________________________________
pre-wrap |  Whitespace is preserved by the browser. 
         |  Text will wrap when necessary, and on line breaks.
_________|_________________________________________________________________________
initial  |  Sets this property to its default value.
_________|_________________________________________________________________________
inherit  |  Inherits this property from its parent element.
_________|_________________________________________________________________________
&#13;
var msg = "h  e  l  l  o";

$('#messages').append($('<li style="background: #ffffff;">' + msg + '</li>'));
$('#messages2').append($('<li style="background: #ffffff;">' + msg + '</li>'));
&#13;
#messages li {
  white-space: pre
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您应该将msg附加到预标记,这将阻止浏览器格式化文本:

$('#messages').append($('<li style="background: #ffffff;"><pre>' + msg + '</pre></li>'))