2010-04-20 11 views
24

używam następujących,Jak uzyskać znacznik span wewnątrz div w jQuery i przypisać tekst?

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

Teraz chcę znaleźć rozpiętość wewnątrz div i przypisać do niego tekstu ...

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

Odpowiedz

45

Spróbuj tego:

$("#message span").text("hello world!"); 

Zobacz to w swoim kodzie!

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, przepraszam za edycję. – rahul

+0

@rahul, byłem trochę zdezorientowany. Bez obaw :) –

4

Spróbuj

$("#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, prawdopodobnie powinieneś ustawić tekst i związać odbiornik przed wyświetleniem zawartości '# message' –

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

lub

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

lub

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

lub

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

Co powiesz na to, czy masz już obiekt JQuery, który jest" message "? –

+0

@ douglasg14b Mam to samo pytanie. – IanS

+1

robisz coś takiego jak 'message.find (....' – Reigel

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"); 
    }); 
} 
Powiązane problemy