문제

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.

Add an onclick event on anchor tags like this.

<a href="#" onclick="someFun(); return false;">click me</a>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top