[英]jquery $(this).attr(…) returns undefined
我正在嘗試獲取option
元素的標題,但它仍然返回undefined。 這也適用於$(this).attr("name")
...和$(this).attr("value")
,但奇怪的是$(this).val()
有效(如預期的那樣)。 然而,我能夠用$(this).attr("value", "baz")
。
this
指向<select>
元素。 對於所選選項,請使用:
this.options[this.selectedIndex]
完整代碼(您可以安全地解包$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);
});
另一種方法,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
代表了你的代碼。 this
表示已更改的select
元素。 因為select節點沒有title
屬性,所以它是未定義的。 您需要做的是枚舉select的選項列表並找到所選項。 然后,您可以對該項目進行操作以查找如下信息:
var element = $(this.options[this.selectedIndex]);
element.attr('title');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.