简体   繁体   中英

Javascript every href onclick

I am developing an app that stays in the website itself, and I want every link to call a function. I have tried this:

HTML

<a href="index.php">link</a><br>
<a href="news.php">link 2</a>

Javascript

var a = document.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
  a[i].onclick = function () {
    return false
  }
}

What is wrong? It doesn't work.

Since it's not jQuery, you should use the preventDefault function.

var a = document.getElementsByTagName("a");
    for (var i = 0; i < a.length; i++) {
       a[i].onclick = function (e) {
       e.preventDefault();

       doSomething();
    }
}

edit for pure javascript solution

document.addEventListener("click", function(e){
    if (e.nodeName==="A"){
        e.preventDefault();
        return false;
    }
}, false);

This will only add one single event to the document and prevent all clicks on anchor elements only.

I removed the old solution because of the comment, that this wasn't a jquery question

Don't use return false , it does more than you really need. Instead try event.preventDefault()

var a = document.getElementsByTagName("a").forEach(function (e) {
       e.onclick = function (a) {
           doSomething(a);
           return false;
       }
    }
}

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