Javascript 使用文本区域以多行显示文本

Javascript 使用文本区域以多行显示文本,javascript,jquery,html,Javascript,Jquery,Html,我在html中使用文本区域标记,我必须在单独的行中打印成分,但即使使用enter键,当我将文本区域的值传递给变量并打印时,它也会出现在一行中 以下是我的代码片段: <div data-role="fieldcontain"> <label for="name">Ingredients</label> <textarea rows="4" cols="50" id="new_ingredients"> </textar

我在html中使用文本区域标记,我必须在单独的行中打印成分,但即使使用enter键,当我将文本区域的值传递给变量并打印时,它也会出现在一行中

以下是我的代码片段:

<div data-role="fieldcontain">
    <label for="name">Ingredients</label>
    <textarea rows="4" cols="50" id="new_ingredients">

    </textarea>
</div>

$( '#new_recipe' ).live( 'pagebeforeshow',function(event){
    var temp1 = $("#new_ingredients").val();
    $("#testing").text(temp1);
});

<div data-role="page" id="new_recipe">
    <div class="content" id="testing" ></div>
</div>

成分
$('new#recipe').live('pagebeforeshow',函数(事件){
var temp1=$(“#新#配料”).val();
$(“#测试”).text(temp1);
});
请帮助我,当用户按enter键时,如何获取不同行中的数据。请提前感谢。

使用此选项:

$("#testing").html(temp1.replace(/\n\r?/g, "<br />"));
$(“#测试”).html(temp1.replace(/\n\r?/g,“
”);
在文本区域中按“回车”键表示的字符用“\n”表示(有时也用
\r
表示)。但在HTML中显示时,它们在视觉上只意味着一个空间。要显示这些换行符,需要将它们替换为HTML等效元素-

元素

由于

元素现在被添加到
#测试
元素的内容中,因此需要使用
.html()
,而不是
.text()
。否则,HTML将转义,无法正确显示

演示:

试试这个

<script src='http://code.jquery.com/jquery-latest.min.js'></script>
<div data-role="fieldcontain">
        <label for="name">Ingredients</label>
        <textarea rows="4" cols="50" id="new_ingredients">ingredient1&#13;&#10;ingredient2&#13;&#10
        </textarea>
        </div>

<script>
$(document).ready(function(){
var temp1 = $("#new_ingredients").html().replace(/\n/g,"<br>");;
 $("#testing").html(temp1);
})
</script>

<div data-role="page" id="new_recipe">
<div class="content" id="testing" ></div></div>

成分
ingredient1和#13
信贷2和13

$(文档).ready(函数(){
var temp1=$(“#新#配料”).html()。替换(/\n/g,“
”);; $(“#测试”).html(temp1); })

我修改脚本只是为了测试

just FYI live()不推荐使用当前版本看看这个:@knut我尝试使用替换函数,但它在div内容中显示了
标记以及字符串,但仍然没有以单独的行显示。@user2185012是否使用了
$(“#testing”).html()
而不是我建议的
$(“#测试”).text()
?这是正确显示

HTML所必需的,我在answer@lan非常感谢。它起作用了:)@knut:是的,我没有使用.html,因此它不起作用。谢谢:)为了更好地覆盖,请使用
替换(/(\n\r\n)/g,
而不仅仅是
/\n\r?/g