更好地使用
我正在尝试处理一个dropoverride的更改事件,它看起来像这样:
<div>
<select id="serviceLine">
<option selected="selected">--Select Option--</option>
<option>Integration</option>
<option>BPM</option>
<option>GWT</option>
<option>Other</option>
</select>
</div>
现在,我想在用户选择"其他"选项时添加一个文本区域。jQuery看起来像这样:
function otherHandler(){
$(this).siblings("textarea").remove();
if($(this).val()=="Other"){
var textbox="<textarea rows='3'></textarea>";
$(this).parent().append(textbox);
}
}
$("#serviceLine").on("change",function(){otherHandler()});
这不起作用,因为在otherHandler() $(this)
中包含整个窗口的引用,而不仅仅是dropbox。
然而,如果我把jQuery改成这样,它会很好地工作:-
function otherHandler(that){
$(that).siblings("textarea").remove();
if($(that).val()=="Other"){
var textbox="<textarea id='slOther'rows='3'></textarea>";
$(that).parent().append(textbox);
}
}
$("#serviceLine").on("change",function(){otherHandler(this)});
我的问题是,为什么它在第一种情况下不起作用,为什么我们必须明确地传递引用?我是不是错过了什么重要的东西?
在第一种情况下,它不起作用,因为this
是为事件处理程序定义的。
$("#serviceLine").on("change",function(){
// this is accessible here in event handler not in the otherHandler function call
otherHandler();
});
你应该直接通过函数的引用
$("#serviceLine").on("change", otherHandler);
如果您希望可以使用.apply(this)
function otherHandler(){
$(this).siblings("textarea").remove();
if($(this).val()=="Other"){
var textbox="<textarea rows='3'></textarea>";
$(this).parent().append(textbox);
}
}
$("#serviceLine").on("change",function(){
otherHandler.apply(this);
});
Raed this keyword
$("#serviceLine").on("change",function(){
//this --> is local to the function block here you cannot use it outside
});
$("#serviceLine").on("change",function(){otherHandler(this)});
//^
在这里,您将此引用传递给函数,使其工作
更好地使用
$("#serviceLine").on("change", otherHandler);
//^ function name