简体   繁体   English

如何在jQuery中将换行符从HTML div复制到textarea?

[英]How to copy newline characters from HTML div to textarea in jQuery?

Consider the following HTML page fragment: 请考虑以下HTML页面片段:

<div id='myDiv'>
    Line 1.<br />
    Line 2<br />
    These are &ltspecial&gt; characters &amp; must be escaped !@@&gt;&lt;&gt;
</div>
<input type='button' value='click' id='myButton' />
<textarea id='myTextArea'></textarea>

<script>
    $(document).ready(function () {
        $('#myButton').click(function () {
            var text = $('#myDiv').text();
            $('#myTextArea').val(text);
        });
    });
</script>

First, there is a div element with id myDiv . 首先,有一个id为myDiv的div元素。 It contains some text similar to what might be retrieved form a SQL database at runtime in my production web site. 它包含一些类似于我的生产网站中运行时可能从SQL数据库中检索到的文本。

Next, there is a button and a textarea. 接下来,有一个按钮和一个textarea。 I want the text in myDiv to appear in the textarea when the button is clicked. 我希望myDiv中的文本在单击按钮时出现在textarea中。

However, using the code I provided, the line-breaks are stripped out. 但是,使用我提供的代码,删除了换行符。 What can I do about this, taking into consideration that escaping special characters is absolutely non-negotiable? 考虑到逃避特殊字符是绝对不可协商的,我该怎么办呢?

Your code works great for me in both Firefox and Chrome: http://jsfiddle.net/jYjRc/ 您的代码在Firefox和Chrome中都非常适合我: http//jsfiddle.net/jYjRc/

However, if you have a client that doesn't do what you want, replace <br> s with newline characters. 但是,如果你有一个客户,您想要什么,不办,更换<br> s的换行符。

Edit: Tested in IE7 and the code breaks. 编辑:在IE7中测试,代码中断。 So I updated the fiddle with my suggestion: http://jsfiddle.net/jYjRc/1/ 所以我用我的建议更新了小提琴: http//jsfiddle.net/jYjRc/1/

Do your HTML like so: 你的HTML是这样的:

<div id='myDiv'><pre>
Line 1.
Line 2
These are &ltspecial&gt; characters &amp; must be escaped !@@&gt;&lt;&gt;
</pre></div>

And now .text() will return the text exactly as you specify it in the <pre> tag, even in IE. 而现在.text()将完全按照您在<pre>标签中指定的方式返回文本,即使在IE中也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM