2010-04-20 40 views
24

utilizo el siguiente,¿Cómo obtener la etiqueta span dentro de un div en jQuery y asignarle un texto?

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

Ahora quiero encontrar el lapso dentro del div y asignar un texto a ella ...

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

Respuesta

45

Prueba esto:

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

¡Véalo en su código!

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, lo siento por la edición. – rahul

+0

@rahul, estaba un poco confundido. No se preocupe :) –

4

Prueba este

$("#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, probablemente debería establecer el texto y enlazar al oyente antes de mostrar el contenido de '# message' –

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

o

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

o

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

o

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

¿Qué tal si ya tiene el objeto JQuery que es' message'? –

+0

@ douglasg14b Tengo la misma pregunta. – IanS

+1

haces algo como '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"); 
    }); 
} 
Cuestiones relacionadas