触发没有匿名函数的jQuery事件函数

时间:2018-07-20 17:23:05

标签: jquery callback anonymous-function eventtrigger jquery-events

我没有找到要解决的问题的答案。 如果有人可以帮助我,我将不胜感激: 我正在处理JavaScript项目,需要将事件函数作为回调函数的参数传递。 有办法吗?

我知道这可以正常工作

function callback(){
    alert("called!");
}
function trigger_callback(message, callback){
    alert(message);
    callback();
}
trigger_callback("I will call a function", callback);

但是我需要的是这样的

trigger_callback("I will focus an input", $("#input").focus);

我得到了错误:

  

TypeError:this._focus未定义

到目前为止,我一直在使用:

trigger_callback("I will focus an input", function(){$("#input").focus();});

我需要一种更简单的方法。 另外,有人可以解释为什么失败了吗?

1 个答案:

答案 0 :(得分:1)

var $tester = $('#tester');
var $tester2 = $('#tester2');

//focus is called while attached to the $tester, so it's context (this) is the $tester
$tester.focus();

//grabbing the method, you lose the context
//focusMethod does not have a context of the $tester
//it's context, in this case, would be the window as it's a global variable
var focusMethod = $tester.focus;

try {
  focusMethod();
} catch (e) {
  console.log('expected error');
}

//we can use bind, which will create another instance of the method, but
//will force the context on it to be $tester
var forceContext = $tester2.focus.bind($tester2);

forceContext();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tester">
<input type="text" id="tester2">