How to prevent default action for Anchor tag using Javascript?

I am trying to prevent the default action on the binding ("a"). In my script, several html lines are displayed on the fly using ajax (after submitting the form), and I want to add an event listener that

  • performs an action when a new link is clicked

  • Prevent the browser from opening this link.

Here is what I am writing:

a = document.getElementById("new_link");
a.addEventListener("click",function(){alert("preform action");
                                      return false;},false);

I also tried:

a.addEventListener("click",function(e){e.preventDefault(); alert("preform action");});

When I click on the β€œa” link, it shows a warning, but still opens the β€œhref” link, where I want it to display a message and then stop.

Both methods show alerts if they are tied to an existing link, but do not work when connected to newly inserted links (via ajax). This is what I need to do.

Any help / suggestions.

Thank.

+3
5

jQuery, , jQ ( , ), .preventDefault() , .

:

$('a').click( function(e) {
  e.preventDefault();
  alert("perform action");
});
+5

jquery-nolink - :

$('new_link').attr("href", "javascript:void(0);");
+3

, , jQuery.

a = document.getElementById("new_link");
a.addEventListener("click",function(){
     alert("preform action");
     window.event.preventDefault();
},false);
+3

, "javascript: void (0);" "href"

: -

<a href="javascript:void(0)" > some link </a>

, , jQuery

$('link-identifier').attr("href", "javascript:void(0);");
+2

.

example :

 <a href='#link' onClick='return false;' > Prevent Link </a>;

jquery,

$('a').click(function (){

   //or if you want to perform some conditions    
   if(condition){
     // your script
   }

   return false;
});

, ☻

+1

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


All Articles