尝试使用 "this" 而不必使用 "that",同时将函数作为参数传递给 jquery 委托事件处理程序

Attempting to use "this" without having to use "that" while passing functions as parameters to jquery delegate event handlers

假设我有一些 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.

我只是想知道是否有更优雅的解决方案来不必使用 "that" 以及函数 clickFunction() 中的 "this" 实际指的是什么?是否有其他方法可以引用调用函数的上下文而不必将其作为参数传递? 谢谢!

您可以在调用函数时使用如下所示的 .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!");