最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using onclick() inside another function - Stack Overflow

programmeradmin1浏览0评论
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.

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.

Share Improve this question edited May 18, 2017 at 7:49 Andrei Maieras asked Feb 28, 2015 at 18:03 Andrei MaierasAndrei Maieras 7065 gold badges16 silver badges36 bronze badges 1
  • First of all, always use the var keyword. The way you have it now all your variables are not limited to just this function and are probably global! Use strict mode to help avoid mon issues like these. Second, your standardId and fancyId variables seem to be poorly named. getElementById returns a DOM element, not an id – George Mauer Commented Feb 28, 2015 at 18:19
Add a ment  | 

2 Answers 2

Reset to default 3

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

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

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

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.

发布评论

评论列表(0)

  1. 暂无评论