在动态添加的元素的onclick处理程序中引用JavaScript函数

Referencing a JavaScript function in the onclick handler of a dynamically added element

本文关键字:引用 JavaScript 函数 程序 onclick 动态 添加 元素 处理      更新时间:2023-09-26

我正在浏览一堆元素,并希望添加一个链接,该链接将运行一小段JavaScript。我正在做的将一个Chrome扩展中的内容脚本。函数do_somethingmy_func在同一个文件中定义,并且是Chrome扩展的一部分。

my_func看起来像这样:

function my_func() {
    $(".matching_class").each(function() {
        $(this).html('<a href="javascript:do_something();">foo</a>');
    });
}

问题是,当我点击我闪亮的链接时,我会得到这个:

未捕获引用错误:未定义do_something

如何从my_func引用do_something

最好将函数绑定到超链接的点击事件,而不是注入对javascript:my_func()的调用;

以下内容(未经测试):

$(".matching_class").each(function() {
    $this.bind('click', do_something);
});

或具有匿名功能:

$(".matching_class").each(function() {
    $this.bind('click', function() {
        //do_somethintg code
    });
});

尝试将do_something函数放在my_func之前。

这可能是因为当您调用do_something时,它可能找不到my_func,因为它是在my_func之后定义的。

因为JavaScript引擎是一个解释器,它解释JavaScript源代码并相应地执行脚本。