Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在jQuery中获取div中的span标记并分配文本?_Jquery_Find_Elements - Fatal编程技术网

如何在jQuery中获取div中的span标记并分配文本?

如何在jQuery中获取div中的span标记并分配文本?,jquery,find,elements,Jquery,Find,Elements,我用下面的 <div id='message' style="display: none;"> <span></span> <a href="#" class="close-notify">X</a> </div> 试试这个: $("#message span").text("hello world!"); 在代码中看到它 function Errormessage(txt) { var m = $("#m

我用下面的

<div id='message' style="display: none;">
  <span></span>
 <a href="#" class="close-notify">X</a>
</div>
试试这个:

$("#message span").text("hello world!");
在代码中看到它

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");
}
试试这个

$("#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");
    });
}

$("span","#message").text("your text");


香草JS,不带jQuery:

document.querySelector('#message span').innerHTML = 'hello world!'

在所有浏览器中都可用:

它将在标记中找到标记,并将文本设置为span


$('div')。查找('span')。文本('Your text')

@rahul,我有点困惑。不用担心:)@rahul,在显示
#message
的内容之前,您可能应该设置文本并绑定侦听器,如果您已经有了JQuery对象,即
message
?@douglasg14b,我有同样的问题。
$("#message").find("span").text("your text");
$("span","#message").text("your text");
$("#message > a.close-notify").siblings('span').text("your text");
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");
    });
}
document.querySelector('#message span').innerHTML = 'hello world!'