jQuery 将文本添加到 div 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4884021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery add text to span within a div
提问by user472285
<div id="tagscloud">
<span></span>
</div>
How would I do to add some text within the span like code below ?
我将如何在跨度内添加一些文本,如下面的代码?
<span>**tag cloud**</span>
<span>**tag cloud**</span>
Edit: actually the span has an id
编辑:实际上跨度有一个 id
<div id="tagscloud"> <span id="WebPartCaptionWPQ2"></span> </div>
回答by kgiannakakis
You can use:
您可以使用:
$("#tagscloud span").text("Your text here");
The same code will also work for the second case. You could also use:
相同的代码也适用于第二种情况。您还可以使用:
$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");
回答by Scarabeetle
Careful - append()
will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>')
.
小心 -append()
将附加 HTML,如果您一直使用它并且用户将您设置为append('<script>alert("Hello")</script>')
.
Use text()
to replace element content with text, or append(document.createTextNode(x))
to append a text node.
用于text()
用文本替换元素内容,或append(document.createTextNode(x))
附加文本节点。
回答by Anwar Chandra
The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).
.append() 方法将指定的内容作为 jQuery 集合中每个元素的最后一个子元素插入(要将其作为第一个子元素插入,请使用 .prepend())。
$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);