$(this).val()无法使用jQuery从跨度获取文本


97

给定这个html,当我单击它时,我想从中获取“ August”:

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

我试过了

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

但似乎没有用

Answers:


210

代替.val()use .text(),就像这样:

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

或者在jQuery 1.7+ on()live已弃用:

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

.val()用于输入类型的元素(包括文本区域和下拉列表),因为您要处理具有文本内容的元素,请.text()在此处使用。


3
注意:.live()在1.7中已弃用,而在1.9+中已删除
Darren

.html()和.text()都适用于我的span元素。
lft93ryt


8

要检索自动生成的跨度值的文本,只需执行以下操作:

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

5

-以上都不对我有用。因此,这是我制定的解决方案,它使用基本功能,因此可在所有浏览器中一致地工作。希望这可以帮助其他人。使用jQuery 8.2

1)获取“ span”的jQuery对象。2)从上方获取DOM对象。使用jquery .get(0)3)使用DOM对象的innerText获取文本。

这是一个简单的例子

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

的HTML

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

4

您可以使用.html()获取span和的内容div元素的内容。

例:

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

3

开始了:

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

希望能帮助到你;)


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.