You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery中在each循环内调用外部函数时this指向异常的问题求助

问题:调用函数时this指向错误导致样式不生效

场景还原

我有两个独立的jQuery函数,单独运行都正常,但在第二个函数的if语句里调用第一个函数时,只有控制台输出red,文字颜色样式没生效,核心原因是this的指向没正确传递。

第一个正常运行的函数

$(document).find('.entries > div').each(color_red);
function color_red() {
    $(this).css('color','red')
    console.log('red')
}

通过jQuery的each调用时,this会自动绑定到当前遍历的DOM元素,所以能正常设置颜色。

第二个正常运行的函数

$( '.entries > div' ).each(function(){
    var thetab = $(this).attr('tab');
    if(thetab == 'all') {
        $(this).removeClass('hide').addClass( 'show' );
    }
    else {
        $(this).removeClass('show').addClass( 'hide' )
    }           
})

这里的this同样是each回调里的当前DOM元素,逻辑正常执行。

修改后有问题的调用代码

if(thetab == 'all' || thetab == tab) {
    $(this).removeClass('hide').addClass( 'show' );
    color_red(); // 此处调用时this指向错误
}

直接调用color_red()时,this默认指向全局对象(浏览器环境下是window),不是当前的DOM元素,所以$(this)找不到目标元素,颜色设置失效,但console.log不受this影响,所以能正常输出。

解决方法

方法1:用call/apply绑定this

调用时手动把当前的this传给color_red,强制函数内的this指向当前DOM元素:

if(thetab == 'all' || thetab == tab) {
    $(this).removeClass('hide').addClass( 'show' );
    color_red.call(this); // 用call绑定当前this
    // 也可以用 color_red.apply(this); 效果完全一致
}

方法2:修改函数为接收参数的形式

把目标元素作为参数传入函数,彻底避免依赖this的指向,这种方式更直观可控:

// 先修改color_red函数,接收元素参数
function color_red(element) {
    $(element).css('color','red')
    console.log('red')
}

// 调用时传入当前DOM元素
if(thetab == 'all' || thetab == tab) {
    $(this).removeClass('hide').addClass( 'show' );
    color_red(this); // 传入当前元素
}

内容的提问来源于stack exchange,提问作者Kev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:50:44