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

时间:2012-01-10 19:56:59

标签: javascript jquery html

<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();
});

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

7 个答案:

答案 0 :(得分:10)

您只需要重写两个.change来电:

$("#sel").change(showalert);
$("#two").change(showalert);

没有必要在另一个函数中“包装”对showalert的调用 - 它已经是对函数的引用,jQuery将确保将this设置为目标元素。

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

$("#sel,#two").change(showalert);

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

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

暂时将其留作id,您的处理程序就变成了

function showalert() {
    alert(this.options[this.selectedIndex].id);
}

基于http://jsfiddle.net/alnitak/54Pd9/

使用value的工作演示

答案 1 :(得分:4)

this根据您调用函数的方式设置

您应该将this元素作为普通参数传递:

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

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

答案 2 :(得分:3)

$(this)传递给该函数。

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

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

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

从评论中编辑。

注释表明你没有传递一个jQuery对象,事实上它是有意义的,因为它只是额外的代码,应该重构到方法中。

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

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

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

答案 3 :(得分:3)

将其作为参数传递,如

function test(elem) {
  $(elem).text();
}

答案 4 :(得分:2)

您已call()使用showalert作为function context来呼叫this

showalert.call(this);

答案 5 :(得分:2)

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

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

答案 6 :(得分:0)

第1步:在页面开头添加对jquery库的引用。

第2步:将此内容写入head:

中的脚本标记内
$(function(){

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

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

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