나는 말할 수 있기를 원한다.
$(someElem).text('this\n has\n newlines);
브라우저에서 새 줄로 렌더링합니다. 제가 찾은 유일한 해결 방법은 일부 Elem에서 css 속성을 'white-space'로 설정하는 것입니다. 이것은 거의 효과가 있지만, 제가 패딩을 0으로 설정했을 때에도, 텍스트와 일부 Elem의 상단 사이에 짜증날 정도로 큰 패딩이 있습니다. 이것을 없앨 방법이 있나요?
https://css-tricks.com/almanac/properties/w/whitespace/
추신 될 때까지, CSS3, s> < common< /s>; # 39 you& 수동으로로 초기 및 / 또는 후행 공백이 트리밍할 오프하도록; d 할 것이다.
Jquery 객체를 변수로 저장할 경우 이 작업을 수행할 수 있습니다.
<! - begin 스니핏: js 숨기십시오: > 거짓값 -;
var obj = $("#example").text('this\n has\n newlines');
obj.html(obj.html().replace(/\n/g,'<br/>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
끝 - < 스니핏 >;!
원할 경우 이를 이용한 간단한 제크리스테스트 마찬가지로 함수 호출 만들 수도 있습니다 () 가:
<! - begin 스니핏: js 숨기십시오: > 거짓값 -;
$.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');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
끝 - < 스니핏 >;!
제가 사용하는 것은 다음과 같습니다.
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"));
"text" 대신 "html"을 사용하고 "\n"이 발생할 때마다 "
"으로 바꿀 수 있습니다. 하지만 텍스트를 올바르게 이스케이프해야 합니다.
x = x.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/\n/g, '<br>');
꼭 이래야겠어요 제안하세요 사용하여 작업할 수 있는 ' ()', '직접' 소미렘 요소점 교체용으로 .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;
}
이를 통해 호출하십시오.
someElem = nl2br(someElem);