gpt4 book ai didi

javascript - 我将如何通过另一种方法对原始 $(this) 执行一种方法?

转载 作者:行者123 更新时间:2023-11-28 21:05:38 25 4
gpt4 key购买 nike

例如:

function masterMethod(this, action){
// (action); <-- But action requires $(this) to be defined.
}

$(".item").click(function(){
function minorMethod(){
alert($(this));
}
masterMethod($(this), minorMethod)
});

我如何执行该操作并在 masterMethod 中传递 $(this) ?

最佳答案

您可以使用call [MDN] :

function masterMethod(element, action){
action.call(element);
}

$(".item").click(function(){
function minorMethod(){
alert($(this));
}
masterMethod(this, minorMethod)
// or directly here?
// minorMethod.call(this)
});

请注意我所做的两个更改:我没有将 $(this) 传递给 masterMethod,而是传递了 this(DOM 元素),因为在 minorMethod 中,您再次将 this 传递给 jQuery。如果您传递 $(this) 您最终会再次将 jQuery 对象传递给 jQuery,即 $($(this)),这是不必要的。

我不确定它是否真的会引发错误,但无论如何,您都不应该将您的参数命名为 this

关于javascript - 我将如何通过另一种方法对原始 $(this) 执行一种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9955131/

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