简体   繁体   中英

Javascript easy onclick example not working

My test.jsp file:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script  type="text/javascript" src="js/test.js"></script>
</head>

<body>
    <a href='#' id='mylink'>click me</a>
</body>
</html>

My test.js file:

alert("HELLO");

var myLink = document.getElementById('mylink');

myLink.onclick = function(){

    alert("I am a pop up ! ");

}

When I load the test.jsp page the Hello alert appears just fine. However when I click on click me , nothing happens.

At the point your script is running, the rest of the DOM hasn't been created yet.

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>

<body>
    <a href='#' id='mylink'>click me</a>
    <script  type="text/javascript" src="js/test.js"></script>
</body>
</html>

Moving the script tag to the bottom is one way to fix that.

It works fine here. Try wrapping it in an onload event listener to ensure the DOM is ready when the document.getElementById is called on the mylink element.

 window.addEventListener("load", function() { var myLink = document.getElementById('mylink'); myLink.onclick = function() { alert("I am a pop up ! "); } }); 
 <a href='#' id='mylink'>click me</a> 

This is a common issue of timing on how things are loaded into the browser on your page. The browser will run scripts and load HTML as it encounters it from the top down. Your JS file is running at the very top of the page. This means, at the point of its execution, the A HREF tag doesn't exist when you create the onclick event. The big issue is that when you call this line:

 document.getElementById('mylink');

That A HREF tag doesn't yet exist, because the browser hasn't yet made it down the page to that line to load the tag into memory (again, because your JS file is at the top of the page). It's a timing issue. That function call returns null, effectively.

You need to put the event handler creation either on an body.onload event or, since you are using the jQuery library, inside a document.ready event. This delays the onclick event creation until the tag is loaded into memory and ready. For example:

 $(document).ready(function() {
      var myLink = document.getElementById('mylink');
      myLink.onclick = function(){
          alert("I am a pop up ! ");
      }
 });

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