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

时间:2010-04-20 06:36:54

标签: jquery find elements

我使用以下内容,

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

现在我想找到div中的span并为其分配一个文本......

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

5 个答案:

答案 0 :(得分:51)

试试这个:

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

答案 1 :(得分:18)

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

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

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

$("#message > a.close-notify").siblings('span').text("your text");

答案 2 :(得分:4)

试试这个

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

没有jQuery的香草JS:

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

在所有浏览器中可用:https://caniuse.com/#search=querySelector