2010-04-20 48 views
24

我用下面,如何在jQuery中的div中獲取span標記並分配文本?

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

回答

45

試試這個:

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

@macek,對不起編輯。 – rahul 2010-04-20 06:46:00

+0

@rahul,我有點困惑。不用擔心:) – 2010-04-20 06:46:24

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

@rahul,你應該在顯示'#消息'的內容之前設置文本並綁定監聽器。 – 2010-04-20 06:49:38

16
$("#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"); 
+1

如果你已經有了'message'的JQuery對象,那麼怎麼樣? – 2016-01-07 07:15:15

+0

@ douglasg14b我有同樣的問題。 – IanS 2016-02-02 17:13:20

+1

你做了類似'message.find(....' – Reigel 2016-02-02 17:15:43

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"); 
    }); 
} 
相關問題