function htmlForTextWithEmbeddedNewlines(text) {
var htmls = [];
var lines = text.split(/\n/);
// The temporary <div/> is to perform HTML entity encoding reliably.
//
// document.createElement() is *much* faster than jQuery('<div></div>')
// http://stackoverflow.com/questions/268490/
//
// You don't need jQuery but then you need to struggle with browser
// differences in innerText/textContent yourself
var tmpDiv = jQuery(document.createElement('div'));
for (var i = 0 ; i < lines.length ; i++) {
htmls.push(tmpDiv.text(lines[i]).html());
}
return htmls.join("<br>");
}
jQuery('#div').html(htmlForTextWithEmbeddedNewlines("hello\nworld"));
$.fn.multiline = function(text){
this.text(text);
this.html(this.html().replace(/\n/g,'<br/>'));
return this;
}
// Now you can do this:
$("#example").multiline('this\n has\n newlines');
我建议直接使用 someElem元素,因为用 .html()替换也会替换字符串中的其他 HTML 标记。
我的功能是:
function nl2br(el) {
var lines = $(el).text().split(/\n/);
$(el).empty();
for (var i = 0 ; i < lines.length ; i++) {
if (i > 0) $(el).append('<br>');
$(el).append(document.createTextNode(lines[i]));
}
return el;
}