[英]jquery $(this).attr(…) returns undefined
I'm trying to get the title of an option
element, but it keeps returning undefined. 我正在尝试获取
option
元素的标题,但它仍然返回undefined。 This also happens for $(this).attr("name")
…and $(this).attr("value")
, but curiously $(this).val()
works (as expected). 这也适用于
$(this).attr("name")
...和$(this).attr("value")
,但奇怪的是$(this).val()
有效(如预期的那样)。 Yet, I'm able to set the value with $(this).attr("value", "baz")
. 然而,我能够用
$(this).attr("value", "baz")
。
Fiddle: http://jsfiddle.net/jshado1/JgAJC/1/ 小提琴: http : //jsfiddle.net/jshado1/JgAJC/1/
this
points to the <select>
element. this
指向<select>
元素。 For the selected option, use: 对于所选选项,请使用:
this.options[this.selectedIndex]
Full code (you can safely unwrap $opt
's jquery wrapper, and use $opt.title
and $opt.name
, these are safe across all browsers): 完整代码(您可以安全地解包
$opt
的jquery包装器,并使用$opt.title
和$opt.name
,这些在所有浏览器中都是安全的):
$('select').change(function() {
var $opt = $(this.options[this.selectedIndex]),
t = $opt.attr("title"),
n = $opt.attr("name"),
v = this.value;
$("#name").text("name: "+n);
$("#title").text("title: "+n);
$("#value").text("value: "+v);
});
Another method, the jQuery-way is: 另一种方法,jQuery方式是:
$('select').change(function() {
var $opt = $(this).children(':selected'),
t = $opt.attr("title"),
n = $opt.attr("name"),
v = this.value;
$("#name").text("name: "+n);
$("#title").text("title: "+n);
$("#value").text("value: "+v);
});
This is because you have mistaken what this
represents in your code. 这是因为你误会了什么
this
代表了你的代码。 The this
represents the select
element that has changed. this
表示已更改的select
元素。 Because the select node doesnt have a title
attribute, it is undefined. 因为select节点没有
title
属性,所以它是未定义的。 What you would need to do is enumerate over the options list of the select and find the item that is selected. 您需要做的是枚举select的选项列表并找到所选项。 Then, you can operate on that item to find information like so:
然后,您可以对该项目进行操作以查找如下信息:
var element = $(this.options[this.selectedIndex]);
element.attr('title');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.