简体   繁体   中英

Javascript not responding to element click?

This is the piece of code in question:

       ...     
        var btnClick = document.getElementById("button");
        btnClick .addEventListener("click", func, false);
    }
    function func()
    {
        alert("This works");
    }

I don't get any alert box. See any problems?

Which browser are you using? IE doesn't support .addEventListener() until version 9, so you need to say something like this:

var btnClick = document.getElementById("button");

if (btnClick.addEventListener){
  btnClick.addEventListener('click', func, false); 
} else if (btnClick.attachEvent){
  btnClick.attachEvent('onclick', func);
}
// and if you're really keen:
else {
  btnClick.onclick = func;
}

And don't use .getElementById() on an element that hasn't been parsed yet, ie, put the above code either in a document.ready or load event handler, or put it after the element in the page source.

If you do all of the following, this will work:

  1. Wait for the document to load before trying to install the event listener. You can either run this code in a window.onload handler or place the javascript initialization code at the end of the body. You can verify if this is or isn't working by seeing if btnClick is valid or null.
  2. Only run this code in newer browsers that support addEventListener (old versions of IE don't support that).
  3. Make sure there is one and only one element in the page with id="button" .
  4. Make sure there are no javascript errors in your page causing your script to stop running.
  5. Remove the space after btnClick before .addEventListener .

You can see it work here: http://jsfiddle.net/jfriend00/HQ24Z/

Its because of the reason that you have not initialised it....!!!

window.onload = prepareButton;

function prepareButton()
{
    document.getElementById('button').onclick = function()
    {
        alert('you clicked me!');
    }
}

Never use very generic terms such as 'button' as they tend to be reserved and you'll end up ripping your hair out if you're absolutely sure it should work. Use descriptive values for id attributes such as 'form_4_button_submit'.

Also an example of how to do cross-browser event handling...

if (window.addEventListener) {document.addEventListener('keydown',keyPressed,false);}
else {document.attachEvent('onkeydown',keyPressed);}

function keyPressed(evt)
{
 var e = evt || event;
 var key = e.which || e.keyCode;

 switch (key)
 {
  case 77:// M
  alert('m key pressed');
  break;

  case 76://L
  alert('L key pressed');
  break;
 }
}

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