如何在函数中使用$(this)?

Mar*_*ndy 2 html javascript jquery

<select id="sel">
    <option id="1">aa</option>
    <option id="2">bb</option>
    <option id="3">cc</option>
</select>

<select id="two">
    <option id="1">aa</option>
    <option id="2">bb</option>
    <option id="3">cc</option>
</select>


function showalert(){
  alert($(this).find('option:selected').attr('id'));
}

$("#sel").change(function(){
   showalert();
});

$("#two").change(function(){
   showalert();
});
Run Code Online (Sandbox Code Playgroud)

如何$(this)在这些功能中正确使用?现在thisundefined.

Aln*_*tak 10

你只需要重写你的两个.change调用:

$("#sel").change(showalert);
$("#two").change(showalert);
Run Code Online (Sandbox Code Playgroud)

没有必要将调用"包装"到showalert另一个函数内部 - 它已经是对函数的引用,jQuery将确保将this其设置为目标元素.

FWIW,两个选择器甚至可以组合,因为它们具有相同的处理程序:

$("#sel,#two").change(showalert);
Run Code Online (Sandbox Code Playgroud)

此外,你不应该id在你的<option>标签上使用这样的东西. id标签应该在整个文档中是唯一的,直到HTML5甚至不被允许为数字.

它应该是value属性,或者如果您已经将其用于其他data-xxx属性,则属性.

暂时离开它id,你的处理程序就变成了

function showalert() {
    alert(this.options[this.selectedIndex].id);
}
Run Code Online (Sandbox Code Playgroud)

工作演示基于使用valuehttp://jsfiddle.net/alnitak/54Pd9/

  • 我在4秒后发布完全相同的代码;(+ 1 (3认同)