简体   繁体   中英

Convert jquery to javascript, call a function on href click

I am trying to write a pure JavaScript function (means no jquery).When a user clicks a link ( a tag) I wanted to run a javascript function. I Googled for a solution but did't find what I was looking for. Below is the jquery solution, I want a pure JavaScript event listener which listens to a href click. There is no id or class attached to tags. ex: <a href='xxxx'>xxxx</a>

This is what I have (using jquery)

    $('a').click(function(e) { 
         var regExp = new RegExp('//'+location.hostname+'($|/)'); 
         var href = $(this).attr('href');
         if (regExp.test(href)) { e.preventDefault();  
    var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1]; 
activityFeedClick(event,i);  } });

I need to convert the above jquery to javascript, basically I need to convert " $('a').click(function(e) " this to a pure JavaScript event listener.

Thanks.

Short answer:

var myFunction = function(e) { 
     var regExp = new RegExp('//'+location.hostname+'($|/)'); 
     var href = this.href;    // please notice this replacement here
     if (regExp.test(href)) { 
         e.preventDefault();  
         var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1]; 
         activityFeedClick(event,i);  
     } 
}

var links = document.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click', myFunction);
}

You can use "document.getElementsByTagName" to get a nodelist of all "a" elements in the DOM, then loop through them and use "addEventListener".

This has the advantage of being supported in browsers without support for queryselector.

像这样在锚标记上添加onclick事件。

<a href="#" onclick="someFun(); return false;">click me</a>

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