简体   繁体   中英

How can I write a non-clickable link that runs a javascript function upon click?

I know this question was answered before, here: javascript:void(0) or onclick="return false" for <a> - which is better?

However, the solution did not work for me.

Here's the applicable code:

HTML:

<a id="Skip">Skip</a>

Javascript:

   var Skip = document.getElementById("Skip");
   Skip.addEventListener('click', reloadPage(), true);

   function reloadPage() {
        window.location.href = "play.php";
    }

When I click on "Skip," nothing happens. I would like to keep the window.location.href method of reloading as I'd like to add $_GET variables to it.

Skip.addEventListener('click', reloadPage(), true);
//                                       ^^-------------------

Should be:

Skip.addEventListener('click', reloadPage, true);

You want the callback to be reloadPage not what reloadPage returns.

Basically you have pass function pointer to addEventListener. So that when click happen it calls that method. You don't want to call the method coz that return nothing

For eg :

Skip. addEventListener('click', reloadPage, true);

you can also do like what you have written but only if your method return another function

for eg

Skip. addEventListener('click', reloadPage(), true);
function reloadPage() {
     return function(){
        // do something interesting.
     }
}

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