javascript 在另一个函数中使用 onclick()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28785031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:33:22  来源:igfitidea点击:

Using onclick() inside another function

javascript

提问by Andrei Maieras

function layoutMod() {
    standardId = document.getElementById("standard");
    fancyId = document.getElementById("fancy");
    standardId.onclick = function() {
        standard();
    };

    fancyId.onclick = function() {
        fancy();
    };
};

How can I use the onclick events defined above in a function??? Is it a good practice to load the function at page load?? I need to define in a function the onclick event beacuse I don't want to use global variables.

如何在函数中使用上面定义的 onclick 事件???在页面加载时加载函数是一个好习惯吗??我需要在函数中定义 onclick 事件,因为我不想使用全局变量。

采纳答案by Drazzah

It can get messing when you nest functions inside of each other.In this case, I would suggest removing the outer function so that your code looks like this:

当您将函数相互嵌套时,它会变得混乱。在这种情况下,我建议删除外部函数,以便您的代码如下所示:

document.getElementById("standard").onclick = function() {
 standard();
};
document.getElementById("fancy").onclick = function() {
 fancy();
};

The code does not need to be in a function, it will automatically be run on page load. Since you don't want global variables, just don't use variables at all.

代码不需要在函数中,它会在页面加载时自动运行。由于您不需要全局变量,因此根本不要使用变量。

回答by bvaughn

What you've written should work. However, you should note that by not using the varkeyword, you're still creating global variables inside of your function. I would suggest...

你写的应该有效。但是,您应该注意,如果不使用var关键字,您仍然会在函数内部创建全局变量。我会建议...

function onloadHandler() {
    document.getElementById("standard").onclick = function() {
        // Do something
    };

    document.getElementById("fancy").onclick = function() {
        // Do something else
    };
};