为什么当我在单独的函数中使用 $(this) 并在 .each() 中调用它时,它不起作用

Why when I use $(this) in a separate function and I call it inside a .each() it doesn't work?

本文关键字:this 并在 调用 不起作用 each 单独 函数 为什么      更新时间:2023-09-26

我试图制作一个干净的jQuery代码,我把我所有的东西都放在一个函数中,我在"each"中调用。问题是没有任何反应,并且在控制台中没有出现任何错误。

这是一个示例代码:

$(function() {
    $('.myElement').each(function() {
        if($(this).children()) {
            myFunction();
        } else {
            myFunction('.myOtherElement');
        }
    });
});
function myFunction(selector) {
    if(!selector) {
        $(this).html('Finish');
    } else {
        $(this).find(selector).html('Finish');
    }   
}

如果我将我的函数内容放在 .each 中,它可以工作,但在单独的函数中不起作用,我认为它应该可以工作。为什么这段代码不起作用?

在这种情况下,执行上下文(this)是不同的,您可以使用.call()来应用它

$(function() {
    $('.myElement').each(function() {
        if($(this).children()) {
            myFunction.call(this);
        } else {
            myFunction.call(this, '.myOtherElement');
        }
    });
});

问题是你的情况下this不是你在.each里面的对象,而是window的对象。要将this绑定为 jquery 对象,而不必每次都应用上下文,请使用 call 。你可以把它定义为一个jquery插件函数

(function($){
    $.fn.myFunction = function (selector) {
    if(!selector) {
        this.html('Finish'); //notice this here refer to jquery object instead of $(this)
    } else {
        this.find(selector).html('Finish');
    }   
  }
})(jQuery);
$(function() {
    $('.myElement').each(function() {
        if($(this).children()) {
            $(this).myFunction();
        } else {
            $(this).myFunction('.myOtherElement');
        }
    });
});