When adding a string, set in JavaScript, to a textarea value, it seems to convert line breaks fine. However, when grabbing this string from a data attribute, it seems to leave the line breaks as \n
在向textarea值添加字符串(在JavaScript中设置)时,似乎可以很好地转换行。然而,当从一个数据属性中抓取这个字符串时,它似乎把断行符保留为\n
These both have type of string so I am confused how one works but not the other.
它们都有字符串类型,所以我搞不清楚其中一个是如何工作的,而不是另一个。
How can I grab the data attribute and make the line breaks work with a textarea?
如何获取数据属性并使换行符在文本区域中工作?
<div id="test" data-message="this\ntest"></div>
<textarea id="textarea"></textarea>
<textarea id="textarea2"></textarea>
var html = 'this\ntest';
var div = $('#test').data('message');
$('#textarea').val(html);
$('#textarea2').val(div);
JSFiddle例子
2 个解决方案
#1
7
You need to use the HTML character entity for line break within an HTML property:
您需要在HTML属性中使用HTML字符实体进行换行:
<div id="test" data-message="this test"></div>
更新的小提琴
#2
3
When you get it from the data attribute the\n
is becoming escaped so you need to replace it:
当你从数据属性中得到它时,\n就会转义,所以你需要替换它:
$('#textarea2').val(div.replace("\\n","\n"));
例子
#1
7
You need to use the HTML character entity for line break within an HTML property:
您需要在HTML属性中使用HTML字符实体进行换行:
<div id="test" data-message="this test"></div>
更新的小提琴
#2
3
When you get it from the data attribute the\n
is becoming escaped so you need to replace it:
当你从数据属性中得到它时,\n就会转义,所以你需要替换它:
$('#textarea2').val(div.replace("\\n","\n"));
例子