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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3567835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:40:43  来源:igfitidea点击:

$(this).val() not working to get text from span using jquery

jqueryhtml

提问by leora

Giving this html, i want to grab "August" from it when i click on it:

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

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

i tried

我试过

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

but doesn't seem to be working

但似乎不起作用

回答by Nick Craver

Instead of .val()use .text(), like this:

而不是.val()use .text(),像这样:

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

Or in jQuery 1.7+ use on()as liveis deprecated:

或者在 jQuery 1.7+ 中使用on()aslive已弃用:

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

.val()is for input type elements (including textareas and dropdowns), since you're dealing with an element with text content, use .text()here.

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

回答by Matthew Jones

I think you want .text():

我想你想要.text()

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

回答by Holyknight

To retrieve text of an auto generated span value just do this :

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

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

回答by Farjad

-None of the above consistently worked for me. So here is the solution i worked out that works consistently across all browsers as it uses basic functionality. Hope this may help others. Using jQuery 8.2

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

1) Get the jquery object for "span". 2) Get the DOM object from above. Using jquery .get(0) 3) Using DOM's object's innerText get the text.

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

Here is a simple example

这是一个简单的例子

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

HTML

HTML

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

回答by Ari

You can use .html()to get content of spanand or divelements.

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

example:

例子:

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

回答by praguan

Here we go:

开始了:

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

Hope it helps;)

希望能帮助到你;)

回答by graycrow

.val()is for input elements, use .html()instead

.val()用于输入元素,请.html()改用