31

我使用以下,

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

现在我想找到 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");
    });
}
4

6 回答 6

63

试试这个:

$("#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");
}
于 2010-04-20T06:38:14.060 回答
22
$("#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");
于 2010-04-20T06:42:24.843 回答
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");
    });
}
于 2010-04-20T06:40:48.933 回答
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");
    });
}
于 2011-11-09T13:32:13.160 回答
0

原版 JS,没有 jQuery:

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

适用于所有浏览器:https ://caniuse.com/#search=querySelector

于 2019-04-17T10:48:52.117 回答
0

它将在标签中找到标签并将文本设置为跨度。

$('div').find('span').text('你的文字');

于 2021-05-23T06:29:00.780 回答