Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

html - jQuery append text

I want to append some simple data in a div like:

$('#msg').append('Some text');

In the body, i think i will need to place the the html like.

<div id="test">    

<div id="msg"></div>  //show text inside it.

</div>

However, I want to add some CSS to the #msg. For example, background color. Now the problem is that, since the #msg div is present all the time, i see the background color even when the text is not appended to it. I have tried to add css like "display:none, but in that case i can not see the text appended to it. Can i do it so that the #msg div appears inside the #test only when the text is appended to it? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The proper way to append text (constrast with appending HTML) would be:

var someText = "Hello, World!";
$('#msg').append(document.createTextNode(someText));

If someText is coming from user input or anything else, it will be properly HTML-escaped. Which should prevent JavaScript injection, the 3rd most common web security vulnerability in the world.

From https://stackoverflow.com/a/944456/122441


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...