字符串中的换行符

Line breaks in a string

本文关键字:换行符 字符串      更新时间:2023-09-26

脚本#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();
});

返回

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

如何使用换行获得相同的结果

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

来自脚本#2?

使用@Ishita的答案

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

编辑

这是因为当您从占位符属性中读取属性时,它不会被视为换行符,而是一个常规的'n字符串。如果你把绳子改回断线,你就在家里了。

使用

<br/> instead of /n 

或者,如果您正在渲染字符串,

replace /n with <br/>
// this is code for string replacement
replace(/'n/g, "<br />");

基本上,写这个代码

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