jQuery text () 및 개행
말할 수 있고 싶어
$(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, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.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);
CSS 공백 속성을 사용하는 것이 아마도 최상의 솔루션 일 것입니다. Firebug 또는 Chrome 개발자 도구를 사용하여 표시되었던 추가 패딩의 소스를 식별하십시오.
이 시도:
$(someElem).html('this<br> has<br> newlines);
참고URL : https://stackoverflow.com/questions/4535888/jquery-text-and-newlines
'Programing' 카테고리의 다른 글
지정된 수의 문자를 읽는 Linux 명령 (예 : cat) (0) | 2020.08.07 |
---|---|
인라인 함수와 전 처리기 매크로 (0) | 2020.08.07 |
부모 이벤트에서 자식 구성 요소의 함수를 호출하는 방법 (0) | 2020.08.07 |
MySQL에서 값이 정수인지 어떻게 확인합니까? (0) | 2020.08.07 |
포커 봇 물리 치기 (0) | 2020.08.07 |