jQuery append text

不羁岁月 提交于 2019-12-17 22:12:12

问题


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.


回答1:


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



回答2:


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




回答3:


Why not use

$('#msg').html('A styled <span style="background: yellow">paragraph</span>');
$('#msg').show();

Escape when needed.




回答4:


I know this question has been answered with different variations but here is one more. I had a similar requirement so spent a little time trying to find a way to do it.

If you know the structure of a HTML, you can get the contents as HTML using jQuery, next change the contents of the same HTML by adding to it.

var lastPageText = $('#test p').html();
        $('#test p').html( lastPageText + ' &#128578;' )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="test"><p>This is how things go perfecting well<span> even in a span</span></p></div>

Hope the above helps someone looking for similar answer

Cheers




回答5:


Folks you can also use this way to append text.

function escapeHtml(unsafe) {
  return unsafe
     .replace(/&/g, "&amp;")
     .replace(/</g, "&lt;")
     .replace(/>/g, "&gt;")
     .replace(/"/g, "&quot;")
     .replace(/'/g, "&#039;");
}


var text = 'Put any text here';
$('#text').append(escapeHtml(text)).show();

Hope this helps.




回答6:


You can do this using multiple ways. You can create a css class and do this:
Method 1
CSS:

.hello{ background-color: green }

HTML

<div id="msg"></div>

Javascript:

$("#msg").append("hello world").addClass("hello");


Method 2
HTML

<div id="msg" class="hello" style="display:none;"></div>

CSS:

.hello{ background-color: green }

Javascript:

$("#msg").append("hello world").show();


Method 3 HTML:

<div id="msg"></div>


Javascript:

$("#msg").append("hello world").css("background-color","green");


来源:https://stackoverflow.com/questions/6588630/jquery-append-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!