I have this JavaScript function :
function putVote(trackid, vote) {
}
and I call this function trought :
<a href="#" onClick="putVote('data1', 'data2')">Link</a>
I would like to use e.preventDefault();
on putVote()
, but I think I'm wro开发者_StackOverflow中文版ng in some ways. How can I do it?
Cheers
The simplest thing to do would be to return false
from the function in the handler (return false
would only work in putVote
if the handler had return putVote('data1', 'data2)
).
But as Pointy said, a much better technique is to attach the event handler from JavaScript, most easily achieved by using a library/framework such as jQuery or Prototype.
The easiest way:
<a href="#" onClick="putVote('data1', 'data2'); return false;">Link</a>
If you're using jQuery.
JS:
$("#link").click(function(evt) {
evt.preventDefault();
putVote('data1', 'data2');
});
HTML:
<a href="#" id="link">Link</a>
If you're using the latest version of jQuery and the HTML5 doctype.
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>
In your case, the trick with using jQuery-style binding is that you want to be able to pass through element-specific parameters to the handler ("data1", "data2"). The "modern" way to do that would be this:
<a href="#" class='data-clickable' data-click-params='["data1", "data2"]'>Link</a>
Then, in a "ready" handler (or some other appropriate place), you'd bind your handler:
$('a.data-clickable').click(function(e) {
var elementData = $(this).data('click-params');
//
// ... handle the click ...
//
e.preventDefault();
});
The "elementData" variable will end up (in this case, anyway) being an array with two values in it, "data1" and "data2". You can give JSON-notation values to "data-foo" attributes, and when you fetch the attributes with the jQuery ".data()" method it will automatically decode the JSON for you.
精彩评论