2014-04-18 2 views
2

스크립트 # 1 :라인 문자열 나누기

<textarea></textarea> 

$('textarea').each(function() { 
    var $placeholder = "First line\nSecond one"; 
    console.log('[function] shikamo__edit_placholder, data-placeholder: ' + $placeholder); 

    $(this).attr('value', $placeholder); 
    $(this).focus(function(){ 
     if($(this).val() == $placeholder){ 
      // reset the value only if it equals the initial one  
      $(this).attr('value', ''); 
     } 
    }); 
    $(this).blur(function(){ 
     if($(this).val() == ''){ 
      $(this).attr('value', $placeholder); 
     }  
    }); 
    // remove the focus, if it is on by default 
    $(this).blur(); 
}); 

반환

<textarea>First line 
Second one</textarea> 

스크립트 # 2 :

<textarea data-placeholder="First line\nSecond one"></textarea> 

$('textarea').each(function() { 
    var $placeholder = $(this).attr('data-placeholder'); 
    console.log('[function] shikamo__edit_placholder, data-placeholder: ' + $placeholder); 

    $(this).attr('value', $placeholder); 
    $(this).focus(function(){ 
     if($(this).val() == $placeholder){ 
      // reset the value only if it equals the initial one  
      $(this).attr('value', ''); 
     } 
    }); 
    $(this).blur(function(){ 
     if($(this).val() == ''){ 
      $(this).attr('value', $placeholder); 
     }  
    }); 
    // remove the focus, if it is on by default 
    $(this).blur(); 
}); 

반환

,210
내가 스크립트 # 2에서 줄 바꿈

<textarea data-placeholder="First line\nSecond one">First line 
Second one</textarea> 

과 같은 결과를 얻을 수있는 방법

?

답변

2

쓰기

$(this).attr('value', ($placeholder.replace(/\\n/g, "\n"))); 

편집

이 자리에서 속성을 읽을 때이없는 줄 바꿈으로하지만 일반 \n 문자열로 볼 수있어 속성 때문이입니다. 그 문자열을 줄 바꿈으로 바꾸면 집에있게됩니다.

+0

잘 작동합니다. 고마워. –

1

사용

<br/> instead of /n 

아니면 문자열을 렌더링하는 경우,

기본적으로
replace /n with <br/> 
// this is code for string replacement 
replace(/\n/g, "<br />"); 

, Ishita의 대답 @ 사용하여이 코드

$(this).attr('value', ($placeholder.replace(/\n/g, "<br />"))); 
+2

'
'는'textarea'에서 작동하지 않습니다. 맞습니까? – cyborg86pl