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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15894807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:29:41  来源:igfitidea点击:

display text in multiline using text area

javascriptjqueryhtml

提问by user2185012

I am using Text area tag in html and i have to print the ingredients in separate lines but even on using enter key it is coming in a single line when i pass the value of text area to a variable and print it.

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

Following is my code snippet :

以下是我的代码片段:

<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>

Please help me as to how could i get data in different lines when the user presses enter key.Thank you in advance.

请帮助我了解如何在用户按下 Enter 键时获取不同行中的数据。在此先感谢您。

回答by Ian

Use this:

用这个:

$("#testing").html(temp1.replace(/\n\r?/g, "<br />"));

The characters that are represented by pressing the "enter" key in a textarea are represented with "\n" (sometimes with \ras well). But when displaying in HTML, they mean nothing more than a space, visually. To display these newlines, they need to be replaced with the HTML equivalent - <br />elements.

在 textarea 中按“enter”键表示的字符用“\n”表示(有时也用\r)。但是当以 HTML 显示时,它们在视觉上只不过是一个空格。要显示这些换行符,需要将它们替换为 HTML 等效<br />元素-元素。

Since <br />elements are now being added to the #testingelement's contents, you need to use .html(), not .text(). Otherwise, the HTML is escaped and won't display properly.

由于<br />现在正在将#testing元素添加到元素的内容中,因此您需要使用.html(),而不是.text()。否则,HTML 将被转义并且无法正确显示。

DEMO:http://jsfiddle.net/Wkbrn/2/

演示:http : //jsfiddle.net/Wkbrn/2/

回答by alwaysLearn

Try this

试试这个

<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>

I have modified the script just for testing

我修改了脚本只是为了测试