JQuery - How to use e.preventDefault (); in javascript function

I have this JavaScript function:

function putVote(trackid, vote) { } 

and I call this function:

 <a href="#" onClick="putVote('data1', 'data2')">Link</a> 

I would like to use e.preventDefault(); on putVote() , but I think I'm wrong in some way. How can i do this?

Greetings

+4
source share
4 answers

The easiest way to do this is: return false from a function in the handler ( return false will only work in putVote if the handler had return putVote('data1', 'data2) ).

But, as Wakey said, itโ€™s much better to use JavaScript event handler binding, which is easy to achieve using a library / framework like jQuery or Prototype.

+5
source

The easiest way:

 <a href="#" onClick="putVote('data1', 'data2'); return false;">Link</a> 
+5
source

If you are using jQuery.

JS:

 $("#link").click(function(evt) { evt.preventDefault(); putVote('data1', 'data2'); }); 

HTML:

 <a href="#" id="link">Link</a> 

If you are using the latest version of jQuery and doctype HTML5.

JS:

 $("#link").click(function(evt) { evt.preventDefault(); var $self = $(this); putVote($self.data("one"), $self.data("two")); }); 

HTML:

 <a href="#" id="link" data-one="data1" data-two="data2">Link</a> 
+5
source

In your case, the trick using jQuery style bindings is that you want to be able to pass element parameters to the handler ("data1", "data2"). The โ€œmodernโ€ way to do this is as follows:

 <a href="#" class='data-clickable' data-click-params='["data1", "data2"]'>Link</a> 

Then, in the "finished" handler (or in another suitable place), you will attach the handler:

 $('a.data-clickable').click(function(e) { var elementData = $(this).data('click-params'); // // ... handle the click ... // e.preventDefault(); }); 

The variable "elementData" will ultimately (in this case) be an array with two values โ€‹โ€‹in it, "data1" and "data2". You can assign the JSON notation values โ€‹โ€‹to the "data-foo" attributes, and when you extract the attributes using the jQuery ".data ()" method, it will automatically decrypt the JSON for you.

+1
source

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


All Articles