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

jQuery load回调改用fillB命名函数后,如何正确执行$('#b')选择器并传参?

问题:jQuery load回调改用命名函数后无法找到加载的DOM元素

通过$('#a').load('test2.html')将包含div#b的test2.html页面内容加载到div#a中,原本使用匿名回调能正常操作#b,但替换为可复用的命名函数fillB()后,选择器$('#b')返回undefined。同时希望能控制传入fillB()的参数。

原代码如下:

<html>
    <head>
      <script src="scripts/jquery.js"></script>
    </head>
    <body>
        <script>
            document.addEventListener('DOMContentLoaded', e => {
                $('#a').load('test2.html', {},
                    // function() {
                        // console.log($('#b').attr('id')); // 返回"b"
                        // $('#b').html('content in #b');
                        // console.log('completed');
                    // }
                    fillB()
                );
            });
            function fillB(option=null) {
                console.log($('#b').attr('id'));//返回undefined :(
                $('#b').html('content in #b: '+option);
                console.log('completed');
            }
        </script>
        <div id="a">placeholder</div>
    </body>
</html>

test2.html内容:

<div id="b"></div>

问题原因

你现在写的fillB()是立即执行函数,相当于把fillB()的返回值(这里是undefined)传给load作为回调,而不是把fillB函数本身作为回调。此时load还没完成加载test2.html,DOM中不存在#b,自然无法找到元素。而原来的匿名函数是将函数本身传递给load,等加载完成后才会执行,这时候#b已经存在于DOM中了。


解决方案

1. 不传参:传递函数引用

把fillB()改成fillB,直接传递函数本身作为回调,load完成后会自动调用它:

document.addEventListener('DOMContentLoaded', e => {
    $('#a').load('test2.html', {}, fillB); // 去掉函数后的括号
});
function fillB(option=null) {
    console.log($('#b').attr('id')); // 正常返回"b"
    $('#b').html('content in #b: '+option);
    console.log('completed');
}

2. 需要传参:两种实现方式

方式A:匿名函数包裹(直观易懂)

用匿名函数作为load的回调,在里面调用fillB并传入自定义参数:

document.addEventListener('DOMContentLoaded', e => {
    const customParam = "我的自定义参数";
    $('#a').load('test2.html', {}, () => {
        fillB(customParam);
    });
});
function fillB(option=null) {
    console.log($('#b').attr('id'));
    $('#b').html('content in #b: '+option);
    console.log('completed');
}
方式B:使用bind绑定参数

通过Function.prototype.bind预先绑定参数,再把绑定后的函数传递给load:

document.addEventListener('DOMContentLoaded', e => {
    const customParam = "我的自定义参数";
    // 第一个参数为this上下文(这里不需要可传null),后续为要传递的参数
    $('#a').load('test2.html', {}, fillB.bind(null, customParam));
});
function fillB(option=null) {
    console.log($('#b').attr('id'));
    $('#b').html('content in #b: '+option);
    console.log('completed');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:33:27