I'm trying to write a chatroom in Javascript. It seems as if you send hello
in the message submission box, it places hello
in the message log on everybody's message log. I have also tried to use the native DOM methods, and the same thing happens there too.
The Javascript to place the message in the log is like this:
socket.on('chat message', function(msg){
$('#messages').append($('<li style="background: #ffffff;">' + msg + '</li>'))
})
The HTML of where it would be placed is like this:
<ul id="messages">
</ul>
Can somebody please tell me why this happens, and how I could keep this from happening.
Browsers don't always display breaking whitespace when showing text, you can change that with CSS
#messages li {
white-space: pre;
}
The valid values are as follows
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.
_________|_________________________________________________________________________
var msg = "hello"; $('#messages').append($('<li style="background: #ffffff;">' + msg + '</li>')); $('#messages2').append($('<li style="background: #ffffff;">' + msg + '</li>'));
#messages li { white-space: pre }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="messages"><li>With white-space</li></ul> <ul id="messages2"><li>Without white-space</li></ul>
您应该将msg附加到pre标签,这将阻止浏览器格式化文本:
$('#messages').append($('<li style="background: #ffffff;"><pre>' + msg + '</pre></li>'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.