字符串中的换行符
Line breaks in a string
脚本#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 />")));
相关文章:
- JavaScript字符串中的换行符也保存为.txt
- 如何删除字符串开头和结尾的换行符
- 如何将CSS跨度应用于没有换行符的串联字符串
- 获取字符串中最后一个换行符的最有效方法是什么
- 在不使用HTML的情况下对字符串中的换行符进行编码
- 如何拆分由换行符分隔的字符串
- 字符串中的字符串可以'不能用换行符分隔
- 从ES6到HTML的多行模板字符串不包括换行符
- 换行符及其在 Javascript 中的字符串连接中的作用
- 换行符导致 JavaScript 中的错误“未终止字符串文字”
- JSON 字符串中的换行符不会出现在 JS 对象中
- 包含换行符的字符串
- 在 JavaScript 字符串 (regex) 中插入多个换行符 (CodeMirror)
- 正确转义 javascript json 字符串中的换行符
- 如何检测字符串中的特定范围是否在换行符中
- PHP 字符串包含打印 Javascript 时的换行符问题
- 尝试向字符串中的每个找到的模式添加换行符
- NodeJS Bug?执行在要返回的字符串之前带有换行符的返回语句时出错
- 如何在不丢失换行符和空格的情况下将js字符串变量传递给php
- 带有换行符的JSP+HTML-将其作为字符串获取,并删除"新线”;