How to handle click link in JavaScript?

How can I handle a link that does not have an identifier? It just has a class name, such as "classbeauty".

Now I need to know if the user clicked the link. If I click the link, I just need to call alert("yes link clicked"); .

I do not know how to handle events in JavaScript.

How can i do this?

+4
source share
6 answers

If jQuery is an option:

  $("a.classbeauty").click(function(){ alert("yes link clicked"); }); 

If you need pure JavaScript:

 var elements = document.getElementsByTagName("a"); for(var i=0; i<elements.length; i++){ if (elements[i].className == 'classbeauty') { elements[i].onclick = function(){ alert("yes link clicked!"); } } } 

If you need it in Greasemonkey :

 function GM_wait() { if(typeof unsafeWindow.jQuery != 'function') { window.setTimeout(wait, 100); } else { unsafeWindow.jQuery('a.classbeauty').click(function(){ alert('yes link clicked'); }); } } GM_wait(); 
+12
source
 function getElementsByClassName(class_name) { var elements = document.getElementsByTagName('*'); var found = []; for (var i = 0; i < elements.length; i++) { if (elements[i].className == class_name) { found.push(elements[i]); } } return found; } getElementsByClassName("YourClass")[0].onclick = function () { alert("clicked"); }; 

This, by the way, is pure javascript. Everyone here loves jQuery (including me).

+2
source
 for (var i= document.links.length; i-->0;) { if (document.links[i].className==='classbeauty') { document.links[i].onclick= function() { alert('yes link clicked'); return false; // if you want to stop the link being followed } } } 
+1
source

If you control the source code, you can add your inline script.

 <a onclick="alert('yes link clicked'); return false">Link</a> 

If you focus on modern browsers, you can select the getElementsByClassName element. Several other people here presented their own implementations of this feature.

 var node = document.getElementsByClassName('classbeauty')[0] node.onclick = function(event){ event.preventDefault() alert("yes link clicked") } 
+1
source
 function handleLinks(className, disableHref) { var links = document.body.getElementsByTagName("a"); for (var i = 0; i < links.length; i++) { if (links[i].className == className) { links[i].onclick = function(){ alert('test') if (disableHref) { return false; //the link does not follow } } } } } handleLinks('test', true) 

you can check it out at this link: http://jsfiddle.net/e7rSb/

0
source

I'm not sure if this is an option, but I would click the flag when the link is clicked, and then just check this variable.

 //javascript var _cbClicked = false; function checkClicked() { if (_cbClicked) alert("link was clicked"); return false; } //html <a href="#" class="classbeauty" onclick="_cbClicked = true; return false;">Link Text</a> <a href="#" onclick="checkClicked();">Check Link</a> 

Very simple and clean JS :)

0
source

Source: https://habr.com/ru/post/1307963/


All Articles