仅当调用 callback [duplicate] 时,才在命名回调函数中评估 jquery 选择器

Evaluate jquery selector in named callback function only when callback is called [duplicate]

提问人:Mister Sir 提问时间:9/14/2023 最后编辑:Mister Sir 更新时间:9/15/2023 访问量:27

问:

我有以下代码,它将div#b加载到div#a中,然后对div#b执行某些操作:

<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')); // returns "b"
                        // $('#b').html('content in #b');
                        // console.log('completed');
                    // }
                    fillB()
                );
            });
            function fillB(option=null) {
                console.log($('#b').attr('id'));//returns 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()在调用时正确执行选择器?$('#b')undefined

编辑:我还希望能够控制传递给哪些参数。fillB()

jQuery AJAX 函数 回调

评论

2赞 mplungjan 9/14/2023
$('#a').load('test2.html', fillB)
0赞 freedomn-m 9/14/2023
.load("..", func())调用结果并将其作为回调传递。 将函数作为回调传递(直到需要它时才调用它)func.load("..", func)

答:

0赞 Mister Sir 9/14/2023 #1

显然,我必须在匿名函数中传递命名的回调函数:

function() { fillB(); }

评论

0赞 mplungjan 9/14/2023
不,没有必要。您可以直接调用该函数,而无需使用括号。查看我的答案和我的评论
0赞 freedomn-m 9/14/2023
.load('..', function() { fillB(); }是一个选项(按原样),但如上所述,不是必需的。要传递函数(不运行它),请使用.load('..', () => fillB() ).load('..', fillB)
1赞 mplungjan 9/14/2023 #2

您可以改为执行此操作。它要短得多,并且出错的地方更少

我还将 vanilla load 事件更改为 jQuery 事件

const fillB = () => {
  $('#b').html('content in #b');
};

$(function() {
  $('#a').load('test2.html', fillB);
});

评论

0赞 Mister Sir 9/14/2023
线索在里面,在后面不加?const()fillB
0赞 mplungjan 9/14/2023
线索是缺失的 (),我们不想在加载后运行它。如果这不起作用,那么您确实需要作为匿名函数$('#a').load('test2.html', () => fillB());
0赞 Mister Sir 9/14/2023
好的,知道了。我必须通过才能不传递任何参数。() => fillB()
0赞 freedomn-m 9/14/2023
我必须通过 - 不,有选择。请参阅此答案中的代码 - 它不会传递匿名函数来设置没有参数的回调。
1赞 freedomn-m 9/15/2023
任何对你有用的东西。SO 旨在提供问题+答案以供将来参考。如果你问“为什么会立即运行”,然后回答“我必须使用”,那么它会让未来的读者感到困惑,他们可能不知道各种变体之间的区别。, fillB()() => fillB()