简体   繁体   中英

Attaching onclick event to element is not working

I just started learning Javascript, and I know next to nothing. I am trying to attached an onclick event to an element in my HTML.

var joinList = function() {
    alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;

This is my code so far. Nothing happens when the element with the ID of header is clicked on. What am I doing wrong?

the following is my HTML code

<!DOCTYPE html>
<html>
    <head>
        <title>Testing Page</title>
        <script src="testing.js"></script>
    </head>

    <body>
        <h1 id="header">Andrew Dawson</h1>
    </body>
</html>

The issue is, that you try to load a html element, which does not "exists" when the javascript function is executed, because the dom has not finished loading. To make your code work, you can try following solutions:

Place your script tag below in the HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Testing Page</title>
    </head>

    <body>
        <h1 id="header">Andrew Dawson</h1>
        <script src="testing.js"></script>
    </body>
</html>

Add an event handler to check if the window element is ready:

window.addEventListener("load", eventWindowLoaded, false);

function eventWindowLoaded(){

    var joinList = function() {
        alert("This should display when clicked");
    }
    document.getElementById("header").onclick = joinList;

}

Another solution would be to use jquery framework and the related document ready function http://api.jquery.com/ready/

I think the solve you are looking for is

var joinList = function() {
    alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);

Your code seems straight forward, maybe your script is running before the DOM fully loads. To keep it simple across all browsers we can place a self executing anonymous function at the end to initiate all your scripts after DOM loads.

  <html>
  <title></title>
  <head></head>
  <body>
  html here!!
  <script>

    (function() {  
       //Any other scripts here

       var joinList = function() {
             alert("This should display when clicked");
         }
       document.getElementById("header").onclick = joinList;


     })();

   </script>
   </body>
   </html>

The above is purely javascript, not to be confused with the shorthand (see below) of the jquery "document onready" function (you would need to add jquery to your pages).

$(function() {
        //your javascript code here
});

Why using self executing function?

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