jQuery 附加文本
我想在 div 中附加一些简单的数据,例如:
$('#msg').append('Some text');
在正文中,我想我需要放置 html 之类的。
<div id="test">
<div id="msg"></div> //show text inside it.
</div>
但是,我想向 #msg
添加一些 CSS。例如,背景颜色。现在的问题是,由于 #msg
div 始终存在,即使文本未附加到它,我也会看到背景颜色。我尝试添加像“display:none”这样的CSS,但在这种情况下我看不到附加到它的文本。 我可以这样做,以便仅当文本附加到 #msg
div 时才出现在 #test
中吗?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
附加文本的正确方法(与附加HTML对比)是:
如果
someText
来自用户输入或其他任何内容,它将是正确的 HTML 转义。这应该可以防止 JavaScript 注入,这是世界上第三大最常见的网络安全漏洞。来自https://stackoverflow.com/a/944456/122441
The proper way to append text (constrast with appending HTML) would be:
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
使用Escape。
为什么不在需要时
Why not use
Escape when needed.
我知道这个问题已经有不同的答案,但这里还有一个。我有类似的要求,所以花了一点时间试图找到一种方法来做到这一点。
如果您知道 HTML 的结构,您可以使用 jQuery 获取 HTML 内容,然后通过添加内容来更改同一 HTML 的内容。
希望以上内容可以帮助寻找类似答案的人
干杯
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.
Hope the above helps someone looking for similar answer
Cheers
您可以使用多种方法来完成此操作。您可以创建一个 css 类并执行以下操作:
方法1
CSS:
HTML
JavaScript:
方法2
HTML
CSS:
Javascript:
方法3
HTML:
JavaScript:
You can do this using multiple ways. You can create a css class and do this:
Method 1
CSS:
HTML
Javascript:
Method 2
HTML
CSS:
Javascript:
Method 3
HTML:
Javascript: