[英]Adding html and plain text inside div with jQuery
I'm recieving a string (it may be either plain text or HTML text) from server, and I need to insert it into a div after that. 我正在从服务器收到一个字符串(可能是纯文本或HTML文本),然后我需要将它插入到div中。
I can use $div.text(textFromServer)
if I know that textFromServer
is plain text. 如果我知道
textFromServer
是纯文本,我可以使用$div.text(textFromServer)
。
If I know that textFromServer
is html I can do something like $(textFromServer).appendTo($div)
. 如果我知道
textFromServer
是html我可以做类似$(textFromServer).appendTo($div)
事情。
The problem is that I don't know for sure whether textFromServer
is plain or HTML. 问题是我不确定
textFromServer
是纯textFromServer
还是HTML。
So here's the question: is there a elegant and simple solution for my problem? 所以这就是问题:我的问题有一个优雅而简单的解决方案吗? Or do I have to analyse
textFromServer
? 或者我必须分析
textFromServer
?
只需使用html()
:
$div.html(textFromServer);
You're describing jquery.html() . 你正在描述jquery.html() 。
$div.html(textFromServer)
should do the trick. $div.html(textFromServer)
应该可以解决问题。
If there in no particular reason for knowing about data type (text / html) then you can directly assign the text / html to your div using [html()][1]
function like 如果没有特别的理由知道数据类型(text / html)那么你可以使用
[html()][1]
函数直接将text / html分配给你的div
$div.html(textFromServer)
If you are interested in knowing the type of data text / html
then you can store the type of your data (text, html) in hidden
field on server
and access that in javascript / jQuery
. 如果您有兴趣了解数据
text / html
的类型,那么您可以将数据类型(text,html)存储在server
上的hidden
字段中,并在javascript / jQuery
访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.