你如何在jQuery中保留textarea中的换行符? [英] How do you preserve the line breaks in a textarea in jQuery?
问题描述
我知道我的问题与此非常相似: jQuery text()函数在IE中丢失换行符,但我的需求略有不同。
I know that my question is very similar to this one: jQuery text() function loses line breaks in IE, but my needs are slightly different.
我的页面上有一个带有模板字符串的textarea要由用户输入的文本。 (它允许他们编写一条消息,使用%NAME%作为名称的占位符。)
I have a textarea on my page that has a "template" string of text to be inputted by the user. (It lets them write a message, using %NAME% as a place holder for the name.)
用户完成模板后,我将其放入第二个textarea,实际上应该使用任何名称替换%NAME%。我已经涵盖了该功能的一部分,并且它运行良好。
After the user finishes the "template", I put it into a second textarea that actually replaces %NAME% with whatever name should be used. I've got that part of the function covered, and it works perfectly.
第二部分在大多数浏览器中也能正常工作。
The second part works fine in most browsers, too.
但是,在Internet Explorer中,第一个textarea的换行符不会保留到第二个。例如,如果用户输入第一个框:
However, in Internet Explorer, the line breaks from the first textarea are not preserved to the second. So for example, if the user entered into the first box:
Hi %NAME%,
How are you?
替换文字的名称是Zak,第二个框显示为:
And the name to replace the text was "Zak", the second box would display as:
Hi Zak,How are you?
将文本输入第二个框的代码是:
My code to get the text into the second box is:
var inviteTemplate=$('#invitationTemplate').text();
inviteTemplate=inviteTemplate.replace(/%NAME%/g,name);
$('#invitationText').html(inviteTemplate);
我假设问题在于使用 .text()
获取textarea的内容。有什么方法可以让IE保留换行符到第二个textarea?
I'm assuming that the problem is with using .text()
to get the contents of the textarea. Is there any way that I can make IE preserve the line breaks into the second textarea?
推荐答案
我可以在IE9 beta中确认,您可以将文本从一个TEXTAREA元素传输到另一个TEXTAREA元素,并保留换行符。
I can confirm that in IE9 beta, you can transfer the text from one TEXTAREA element to another TEXTAREA element with the line-breaks preserved.
现场演示: http ://jsfiddle.net/LWjP6/1/
这篇关于你如何在jQuery中保留textarea中的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!