在 jQuery.on() 事件调用的现有 Javascript 函数中使用 "this" 作为参数

Using "this" as parameter in an existing Javascript function called by jQuery.on() event

问题:

我的 HTML 代码中有一些 selectsoptions,我设置了一个 on change event handler,以确定何时更改选择。

下面的代码显示了 jQuery 获取 on change 的代码:

 $(document).on('change', '.anyHtmlSelect', updateState);

我有一个现有的 Javascript 函数,应该用作回调函数。

Javascript 函数如下所示:

function updateState(element) 
{  
    var currentId = element.attr("id");
}

问题:

如何将 更改为 selectelement

我试过以下方法:

 $(document).on('change', '.anyHtmlSelect', updateState($(this));

但是没用。

经过一番研究,我找到了一个解决方案,我将与您分享。

在我的解决方案中,我创建了一个 匿名函数 ,它以 $(this) 作为参数调用 updateState 函数。

$(document).on('change', '.anyHtmlSelect', function () {
    updateState($(this));
});

有更好的解决方案吗?

自动传递给事件处理程序的第一个参数是对事件本身的引用,而不是引发事件的元素。要访问触发事件的 DOM 元素,请使用 this:

只需更改:

function updateState(element) 
{  
    var currentId = element.attr("id");
}

至:

function updateState(event) {  
    var currentId = this.attr("id");
}