jQuery:将 TextArea 内容转换为 html 字符串,反之亦然

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3804104/
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-08-26 16:08:04  来源:igfitidea点击:

jQuery: Convert TextArea content to html string and vice versa

jqueryhtmlstring

提问by iakko

what I'm trying to do is converting a TextArea content into a valid html code. Suppose you type inside the TextArea and then you press a button that shows the typed text inside a element. If you typed something like inside the TextArea:

我想要做的是将 TextArea 内容转换为有效的 html 代码。假设您在 TextArea 内键入,然后按下一个按钮,显示元素内键入的文本。如果您在 TextArea 中输入类似内容:

Hi folks!
Do you like jQuery?
I do!

嗨伙计!
你喜欢 jQuery 吗?
我愿意!

The resulting string you have to put inside the '' element is:

您必须放入 '' 元素的结果字符串是:

Hi folks!<br>Do you like jQuery?<br>I do!

That's because the newline inside the TextArea must be converted to the <br>tag!

那是因为必须将 TextArea 内的换行符转换为<br>标签!

The same thing should happend if you want to take the html of the element and put it inside the TextArea input field, for example:

如果您想获取元素的 html 并将其放入 TextArea 输入字段中,也会发生同样的事情,例如:

Hi folks!<br>Do you like jQuery?<br>I do!

should be converted to:

应转换为:

Hi folks!
Do you like jQuery?
I do!

嗨伙计!
你喜欢 jQuery 吗?
我愿意!

So, is there a way to convert a string to html-string (and vice versa) or should I write a function by myself?

那么,有没有办法将字符串转换为 html 字符串(反之亦然),还是我应该自己编写一个函数?

Thanks in advance!

提前致谢!

回答by Andy E

With the appropriate styling on the element, you shouldn't need to convert anything. Using the CSS white-spaceproperty with a value set to pre, any white-space in the element should appear exactly as it does in the textarea:

使用适当的元素样式,您不需要转换任何内容。使用值设置为pre的 CSS white-space属性,元素中的任何空白都应该像在 textarea 中一样显示:

#myElement { white-space: pre; }

Example: http://jsfiddle.net/TkpSu/

示例:http: //jsfiddle.net/TkpSu/

回答by Tatu Ulmanen

Well, it's not very difficult:

嗯,这不是很难:

$('#element').html($('textarea').html().replace(/\n/g, "<br />"));

回答by Stephen

Consider looking into a markdown editor. Stack overflow uses a modified version of this one: http://wmd-editor.com/

考虑研究降价编辑器。堆栈溢出使用此版本的修改版本:http: //wmd-editor.com/