jQuery $(this).val 返回 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7490010/
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 23:55:07  来源:igfitidea点击:

jQuery $(this).val returns 0

jquery

提问by HymanBurton

I have a simple list like this:

我有一个像这样的简单列表:

<ul id="large_box_custom_list">
<li id="8" class="large_box">Item 1</li>
<li id="13" class="large_box">Item 2</li>
</ul>

then I have a jQuery function like this:

然后我有一个像这样的 jQuery 函数:

$(function() { 
$('li.large_box').css('cursor', 'pointer')
.click(function() {
    var show_id = $(this).val();
    alert(show_id);
    });
});

When I click the list items my alery shows a value of 0 when I am expecting a value of 8 or 13.

当我单击列表项时,当我期望值为 8 或 13 时,我的 alery 显示值为 0。

回答by Matt Ball

Because you should be using the standard DOM element idproperty. jQuery's .val()method has nothingto do with an element's ID.

因为您应该使用标准的 DOM 元素id属性。jQuery 的.val()方法与元素的 ID无关

$('li.large_box').css('cursor', 'pointer').click(function ()
{
    var show_id = this.id;
    alert(show_id);
});

回答by Chris G.

val()doesn't return the id. You want $(this).attr('id')instead.

val()不返回 ID。你想要$(this).attr('id')

回答by zzzzBov

You're doing it wrong.

你这样做是错的。

the idattribute is meant to be used as a unique identifier, not as a means of data-storage.

id属性旨在用作唯一标识符,而不是用作数据存储手段。

Additionally, .val()is meant to be used on input, select, textareaelements to access their current values.

此外,.val()旨在用于input, select, textarea元素以访问其当前值。

If you need an element's attribute use the .attr()function.

如果您需要元素的属性,请使用.attr()函数

If you need to store data on an element, use a custom HTML5 data-element:

如果需要在元素上存储数据,请使用自定义 HTML5data-元素:

<li data-id="8"...
<li data-id="13"...

You'd then be able to access the value with the .data()function:

然后您就可以使用以下.data()函数访问该值:

var listItemIdentifier = $(this).data('id');
console.log( listItemIdentifier );
//should output 8 or 13 depending on which you click on

回答by Matt Huggins

Try using attr()instead of val():

尝试使用attr()代替val()

$(function() { 
    $('li.large_box').css('cursor', 'pointer').click(function() {
        var show_id = $(this).attr('id');
        alert(show_id);
    });
});

回答by Jaime

use $(this).attr('id')

$(this).attr('id')

<li>can't have a value with out using non standard attributes.

<li>不使用非标准属性就不能有值。

回答by Royi Namir

var show_id = $(this).attr('id');

回答by Drake

A id attribute is not a value attribute.

id 属性不是值属性。

You can either set it up to get the id:

您可以将其设置为获取 id:

$(this).attr("id");

Or set the value in HTML

或者在 HTML 中设置值

<li id="8" value="8" class="large_box">Item 1</li>

Here is a live example: http://jsfiddle.net/BBm4R/

这是一个活生生的例子:http: //jsfiddle.net/BBm4R/