jQuery 如何在jQuery中的div中获取span标签并分配文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2673075/
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
How to get span tag inside a div in jQuery and assign a text?
提问by bala3569
I use the following ,
我使用以下,
<div id='message' style="display: none;">
<span></span>
<a href="#" class="close-notify">X</a>
</div>
Now i want to find the span inside the div and assign a text to it...
现在我想在 div 中找到跨度并为其分配一个文本...
function Errormessage(txt) {
$("#message").fadeIn("slow");
// find the span inside the div and assign a text
$("#message a.close-notify").click(function() {
$("#message").fadeOut("slow");
});
}
回答by ma?ek
Try this:
尝试这个:
$("#message span").text("hello world!");
See it in your code!
在您的代码中看到它!
function Errormessage(txt) {
var m = $("#message");
// set text before displaying message
m.children("span").text(txt);
// bind close listener
m.children("a.close-notify").click(function(){
m.fadeOut("slow");
});
// display message
m.fadeIn("slow");
}
回答by Reigel
$("#message > span").text("your text");
or
或者
$("#message").find("span").text("your text");
or
或者
$("span","#message").text("your text");
or
或者
$("#message > a.close-notify").siblings('span').text("your text");
回答by rahul
Try this
尝试这个
$("#message span").text("hello world!");
function Errormessage(txt) {
var elem = $("#message");
elem.fadeIn("slow");
// find the span inside the div and assign a text
elem.children("span").text("your text");
elem.children("a.close-notify").click(function() {
elem.fadeOut("slow");
});
}
回答by Vinothkumar Arputharaj
function Errormessage(txt) {
$("#message").fadeIn("slow");
$("#message span:first").text(txt);
// find the span inside the div and assign a text
$("#message a.close-notify").click(function() {
$("#message").fadeOut("slow");
});
}
回答by Alexander Kim
Vanilla JS, without jQuery:
Vanilla JS,没有 jQuery:
document.querySelector('#message span').innerHTML = 'hello world!'
Available in all browsers: https://caniuse.com/#search=querySelector
适用于所有浏览器:https: //caniuse.com/#search=querySelector