假设我有一些javascript,我已经成功地将两个事件处理程序连接到DOM无序列表中的所有DOM "li"元素:
function userClickFunction() {
console.log("USER CLICK");
clickFunction(this);//had to pass "this" as parameter
}
function autoClickFunction() {
console.log("AUTO CLICK");
clickFunction(this);//had to pass "this" as parameter
}
function clickFunction(that) {
var clickedItem = $(that).attr('id');//using "that" I was able to get the attrs from the "li" element
console.log("CLICKED!");
}
$("#my_list").delegate("li", "click", userClickFunction);
$("#my_list").delegate("li", "autoClick", autoClickFunction);
然后我在JS的其他地方触发这些事件处理程序。
$("#some_li").trigger('click');//just kidding, the user does this :P
$("#some_li").trigger('autoClick');//fired by comparing some elaborate timers and interesting state variables.
我只是想知道是否有一个更优雅的解决方案,不必使用"那"和什么"这个"在函数clickFunction()实际上指的是?是否有其他方法可以引用调用函数的上下文而不必将其作为参数传递?谢谢你!
在调用函数时可以使用.call()传递自定义上下文,然后可以在回调函数中使用this
function userClickFunction() {
console.log("USER CLICK");
clickFunction.call(this); //had to pass "this" as parameter
}
function autoClickFunction() {
console.log("AUTO CLICK");
clickFunction.call(this); //had to pass "this" as parameter
}
function clickFunction() {
var clickedItem = this.id; //now this refers to the `li` element, also to get the `id` just refer to `this.id` no need to call `attr()`
console.log("CLICKED!");