jQuery text () 및 개행 싶어 $(someElem).text(‘this\n has\n newlines); 브라우저에서 줄 바꿈으로

말할 수 있고 싶어

$(someElem).text('this\n has\n newlines);

브라우저에서 줄 바꿈으로 렌더링됩니다. 내가 찾은 유일한 해결 방법은 someElem에서 css 속성 ‘white-space’를 ‘pre’로 설정하는 것입니다. 이것은 거의 작동하지만 패딩을 0으로 설정하더라도 텍스트와 someElem의 상단 사이에 성가 시게 큰 패딩이 있습니다. 이것을 제거하는 방법이 있습니까?



답변

2015 년입니다.이 시점에서이 질문에 대한 정답은 CSS를 사용 white-space: pre-line하거나white-space: pre-wrap . 깨끗하고 우아합니다. 쌍을 지원하는 IE의 가장 낮은 버전은 8입니다.

https://css-tricks.com/almanac/properties/w/whitespace/

PS CSS3가 일반화 될 때까지 초기 및 / 또는 후행 공백을 수동으로 제거해야 할 것입니다.


답변

jQuery 객체를 변수에 저장하면 다음과 같이 할 수 있습니다.

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>

원하는 경우 jQuery.text ()처럼 간단한 호출로이를 수행하는 함수를 만들 수도 있습니다.

$.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"));

답변

또한, 사용하려고 .html하고 포장<pre>태그 :

$(someElem).html('this\n has\n newlines').wrap('<pre />');

답변

html대신 사용 text하고의 각 항목을 \n로 바꿀 수 있습니다 <br>. 그래도 텍스트를 올바르게 이스케이프해야합니다.

x = x.replace(/&/g, '&amp;')
     .replace(/>/g, '&gt;')
     .replace(/</g, '&lt;')
     .replace(/\n/g, '<br>');

답변

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

전화 :

someElem = nl2br(someElem);

답변

이 시도:

$(someElem).html('this<br> has<br> newlines);