jQuery:将TextArea内容转换为html字符串,反之亦然 [英] jQuery: Convert TextArea content to html string and vice versa

查看:201
本文介绍了jQuery:将TextArea内容转换为html字符串,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做的是将TextArea内容转换为有效的HTML代码。假设你在TextArea中键入内容,然后按下一个按钮,该按钮在元素内显示键入的文本。如果你在TextArea里面输入类似的东西:


你喜欢jQuery吗?

你喜欢jQuery吗?
$


您必须将结果字符串放入''元素中:

  Hi folks!< br>你喜欢jQuery吗?< br>我做到了! 

这是因为TextArea内的换行符必须转换为< br> ; tag!



如果您想将元素的html放入TextArea输入字段中,例如:

  Hi folks!< br>你喜欢jQuery吗?< br>我做的! 

应该转换为:


伙计们!

您喜欢jQuery吗?

我做!

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



解决方案

使用适当的元素样式,您不需要转换任何东西。使用设置为 pre 的CSS white-space 属性,元素中的任何空格应该与textarea中的空格完全相同:

  #myElement {white-space:pre; } 

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


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:

Hi folks!
Do you like jQuery?
I do!

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!

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:

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

should be converted to:

Hi folks!
Do you like jQuery?
I do!

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

Thanks in advance!

解决方案

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

#myElement { white-space: pre; }

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

这篇关于jQuery:将TextArea内容转换为html字符串,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆