2010-08-25 11 views
73

Dar este html, quiero agarrar "Agosto" de que cuando hago clic en él:Obtener texto de lapso usando jQuery

<span class="ui-datepicker-month">August</span> 

Traté

$(".ui-datepicker-month").live("click", function() { 
    var monthname = $(this).val(); 
    alert(monthname); 
}); 

pero no parece estar trabajando

Respuesta

175

En lugar de utilizar .val().text(), así:

$(".ui-datepicker-month").live("click", function() { 
    var monthname = $(this).text(); 
    alert(monthname); 
}); 

O en jQuery 1.7+ utilizar on() como live es obsoleto:

$(document).on('click', '.ui-datepicker-month', function() { 
    var monthname = $(this).text(); 
    alert(monthname); 
}); 

.val() es para elementos de tipo de entrada (incluyendo las áreas de texto y menús desplegables), ya que está tratando con un elemento con el contenido del texto, utilice .text() aquí .

+2

NOTA: '.live()' está en desuso en 1.7 yr eliminado en 1.9+ – Darren

+0

Ambos .html() y .text() funcionaron para mi elemento span. – lft93ryt

17

Creo que quieres .text():

var monthname = $(this).text(); 
0

.val() es para elementos de entrada, utilice .html() lugar

4

-Ninguno de los anteriores trabajado constantemente para mí. Así que aquí está la solución que encontré que funciona de manera consistente en todos los navegadores, ya que utiliza una funcionalidad básica. Espero que esto ayude a otros. Usando jQuery 8.2

1) Obtenga el objeto jquery para "span". 2) Obtiene el objeto DOM desde arriba. Usando jquery .get (0) 3) Utilizando el texto interno del objeto DOM obtener el texto.

Aquí está un ejemplo sencillo

var curSpan = $(this).parent().children(' span').get(0); 
var spansText = curSpan.innerText; 

HTML

<div > 
<input type='checkbox' /><span >testinput</span> 
</div> 
3

Puede utilizar .html() para obtener el contenido de span y div o elementos.

ejemplo:

var monthname = $(this).html(); 
    alert(monthname); 
6

Para recuperar texto de un valor de calibración automática generada simplemente hacer esto:

var al = $("#id-span-name").text();  
alert(al); 
0

Aquí vamos:

$(".ui-datepicker-month").click(function(){ 
var textSpan = $(this).text(); 
alert(textSpan); 
}); 

creo que sirve;)

Cuestiones relacionadas