将js附加到html按钮

时间:2014-03-05 22:30:47

标签: javascript html

我正在尝试将此脚本附加到HTML按钮,但似乎无法理解它。

使用Javascript:

var $ = function (id) {
        return document.getElementById(id);
        if (getElementById(button));    
        var sumOfNumbers = 0;
        var numberOfLoops = 20;
        var counter = 1;
        while (counter <= numberOfLoops){
            alert(sumOfNumbers);
            sumOfNumbers += counter;
            counter++;
        }
}    

HTML:

<p><input type="button" id="button" value="Loop"/></p>

1 个答案:

答案 0 :(得分:0)

为什么不直接向按钮添加事件监听器?

参见 DEMO

var button = document.getElementById('button');

if (button.addEventListener){
    button.addEventListener('click', function() { $(); });    
} else if (button.attachEvent){ // IE < 9 :(
    button.attachEvent('onclick', function() { $(); });
}

var $ = function() {
        var sumOfNumbers = 0;
        var numberOfLoops = 20;
        var counter = 1;
        while (counter <= numberOfLoops){
            alert(sumOfNumbers);
            sumOfNumbers += counter;
            counter++;
        }
} 

此外,如果您有Firebug或Chrome开发者控制台,请通过alert()电话交换console.log()来电。警报可能会很烦人,特别是如果它们背靠背地显示;连续。

本地文件示例:

<html>
    <head>
        <script type="text/javascript">
        var ready = function() {
            var button = document.getElementById('button');

            if (button.addEventListener){
                button.addEventListener('click', function() { $(); });    
            } else if (button.attachEvent){ // IE < 9 :(
                button.attachEvent('onclick', function() { $(); });
            }

            var $ = function() {
                var sumOfNumbers = 0;
                var numberOfLoops = 20;
                var counter = 1;
                while (counter <= numberOfLoops){
                    alert(sumOfNumbers);
                    sumOfNumbers += counter;
                    counter++;
                }
            }
        }
        </script>
    </head>
    <body onLoad="ready()">
        <p><input type="button" id="button" value="Loop" /></p>
    </body>
</html>