简体   繁体   中英

Event handlers don't work in js

Why do my event handlers not work in my javascript function.If it's the wrong way to access a button event handler inside a js function than how to do it correctly?

<script type="text/javascript">

function cl(){
    var button = document.getElementById('but');
    button.onclick = function (){
        alert('this works');
    }
}

</script>
</head>
<body>
<input type="button" value = "click" id = "but">
</body>

You have wrapped the event handler method into another method. Call your method and it will work

cl();

However, I'd rather initialise the scripts on that page simply by waiting for the document to load:

  function init() {
      button.onclick = function (){
          alert('this works');
      }
  }
  document.onload = init();

I'd move that script tag containing the JS code after the body tag, just to make it unobtrusive, so that the code should look like:

...
</head>
<body>
<input type="button" value="click" id="but">
<script type="text/javascript">
    function init() {
        var button = document.getElementById('but');
        button.onclick = function (){
            alert('this works');
        }
    }
    document.onload = init();
</script>
</body>

The code in your cl function is not beeing called since the function is not called anywhere.

Either you remove the function declaration like:

function cl(){
   document.getElementById('but').onclick = function() {
   alert('fdsfsdf');
};

Or you call the function to go into the code by calling cl(); :

cl();    
function cl(){
   document.getElementById('but').onclick = function() {
   alert('fdsfsdf');
};

Take a look here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM