0

我是新手,所以这个问题可能听起来很愚蠢。我想加载一个javascript函数, <body onload="function()">但我想通过开/关开关处理这个事件,所以如果开关打开(默认情况下)“onload”事件将调用该函数,如果开关设置为关闭它不会. 提前致谢!

4

2 回答 2

1

If you want to execute a function when the document is loaded, you should use the window onload event, or alternatively, and maybe more accepted solution is to use jquery (look into it, better learn the best practice from the beginning)

$(function(){
    // my_on_load_script;
});

If you'd like to create a toggle button in javascript, you may use jquery (again), to toggle styles applied to the button element something along the lines:

$('#my_button_identifier').click(function(e){
    $(this).toggleClass('my_toggled_button_class');
);

here you go: http://api.jquery.com/toggleClass/

于 2012-04-29T20:36:11.217 回答
0
<h1 id="changetext"> status is here</h1>
<button id="alertme" onclick="bulb();" >ON</button>
<script>
var flag = 0;           
            function bulb(){
                if (flag==0) {
                window.alert(flag);
                document.getElementById('alertme').innerHTML = "OFF";
                document.getElementById('changetext').innerHTML = "Machine is off";
                flag=1;
                }
                else        {
                window.alert(flag);
                document.getElementById('alertme').innerHTML = "ON";
                document.getElementById('changetext').innerHTML = "Machine is on";              
                flag=0;
                }
            }
</script>
于 2016-05-17T00:11:55.393 回答