2013-10-01 5 views
1

)으로 변환하자. 다음 HTML 파일이 있다고 가정 해 보겠습니다.div의 텍스트에서 n을 <br /> (JS

... 
<div class="field"> 
    Lorem ipsum dolor sit amet,\nconsectetuer adipiscing elit. ... 
</div> 
... 
<div class="field"> 
    Phasellus faucibus molestie nisl.\nMorbi leo mi,\nnonummy 
    eget tristique non,\nrhoncus non leo. ... 
</div> 
... 

다음 코드는 HTML과 같은 새로운 라인 (즉 < BR /> 태그)와 \ n 문자를 대체 할 예정이다. 그러나 결과는 < br /> 시퀀스가 ​​그대로 텍스트에 나타나며 페이지에 붙여 넣기 전에 이스케이프 처리 된 것과 같습니다.

$(".field").each(function() 
{ 
    var oldText = $(this).text(); 
    var newText = oldText.replace(/\n/g, "<br />"); 
    $(this).text(newText); 
}); 

라틴어 텍스트를 실제 줄 바꾸기 위해 어떻게 수정합니까? 사용 .html() 대신 .text()

+7

$ (이) .html 중에서 (를 newText); – JonasT

+2

'white-space : pre' – SLaks

+2

@SLaks, 멋진. 이는이 시나리오에서 더 나은 접근 방법입니다. – xandercoded

답변

4

:

$(this).html(newText); 

출처 :

0

http://api.jquery.com/html/는 "필드"의 HTML을 가지고, 다음 HTML 콘텐츠에 대체 방법을. 그렇게하면 "텍스트"가 아닌 필요에 따라 렌더링됩니다. 기본적으로 텍스트가 아닌 HTML로 렌더링해야합니다. 따라서 새 텍스트를 HTML로 바꾸면 올바르게 렌더링됩니다.

Exaample :

$(document).ready(function(){ 
    $(".field").each(function() 
    { 
    var oldText = $(this).text();  
    var newText = oldText.replace(/\n/g, "</br>"); 

    $(this).html(newText); 
    }); 
}); 
+0

죄송합니다, 내 솔루션에서 작업하는 동안 게시했습니다. – Casey

관련 문제