jquery $(this).attr(...)返回undefined

jac*_*cob 2 javascript jquery find switch-statement

我正在尝试获取option元素的标题,但它仍然返回undefined.这也适用于$(this).attr("name")...而且$(this).attr("value"),奇怪的$(this).val()是(正如预期的那样).然而,我能够设定价值$(this).attr("value", "baz").

小提琴:http://jsfiddle.net/jshado1/JgAJC/1/

Rob*_*b W 9

this指向<select>元素.对于所选选项,请使用:

this.options[this.selectedIndex]
Run Code Online (Sandbox Code Playgroud)

完整代码(您可以安全地打开$optjquery包装器,并使用$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);
});
Run Code Online (Sandbox Code Playgroud)

另一种方法,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);
});
Run Code Online (Sandbox Code Playgroud)

  • @EvilP因为你已经交换了选择器,并在`option`和`:selected`之间添加了一个空格.空格分隔子选择器,因此将其删除.此外,`$(selector,context)`是正确的签名(相当于`.find`).因为你使用`> option`,所以选择器相当于`$(this).children('option:selected');`. (2认同)