gpt4 book ai didi

javascript - jQuery:将 $(this) 传递给命名函数事件处理程序

转载 作者:行者123 更新时间:2023-12-03 21:44:06 25 4
gpt4 key购买 nike

我注意到建议use named functions when binding an event handler to a javascript event 。当我的函数需要传递 this 对象时,我该如何做到这一点?

例如,如何通过直接调用doFancyStuff来替换下面的匿名函数:

$(document).on('change', 'input.fancy-textbox', function () {
doFancyStuff($(this));
});

function doFancyStuff($textbox) {
// fanciness
}

如果您指出我可能违反上述代码的其他约定,请加分。

<小时/>

为了澄清,我想从多个地方调用示例中的 doFancyStuff() 方法,否则,我可以这样做:

$(document).on('change', 'input.fancy-textbox', doFancyStuff);

function doFancyStuff() {
var $textbox = $(this);

// fanciness
}

最佳答案

我想说这是一个意见问题。我认为这里使用匿名函数没有问题。如果这是唯一调用 doFancyStuff 的地方,您可以这样做:

$(document).on('change', 'input.fancy-textbox', doFancyStuff);

function doFancyStuff() {
// fanciness
var $textbox = $(this)
}

但是,如果从多个位置调用此函数并且您无法更改它的工作方式,则必须执行以下操作:

$(document).on('change', 'input.fancy-textbox', doFancyStuffFromEvent);

function doFancyStuffFromEvent() {
// fanciness
doFancyStuff($(this));
}

function doFancyStuff($textbox) {
// fanciness
}

这很困惑。

关于javascript - jQuery:将 $(this) 传递给命名函数事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9025294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com