简体   繁体   English

jQuery - 如何使用e.preventDefault(); 在JavaScript函数中

[英]jQuery - How to use e.preventDefault(); in a JavaScript function

I have this JavaScript function : 我有这个JavaScript函数:

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(); 我想使用e.preventDefault(); on putVote() , but I think I'm wrong in some ways. putVote() ,但我认为我在某些方面是错的。 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) ). 做最简单的事情是将return false 从函数 在处理程序( return false只会在工作putVote如果处理程序都有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. 但正如Pointy所说,一种更好的技术是从JavaScript附加事件处理程序,最容易通过使用jQuery或Prototype等库/框架来实现。

最简单的方法:

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

If you're using jQuery. 如果你正在使用jQuery。

JS: JS:

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

HTML: HTML:

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

If you're using the latest version of jQuery and the HTML5 doctype. 如果您使用的是最新版本的jQuery和HTML5 doctype。

JS: JS:

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

HTML: 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"). 在您的情况下,使用jQuery样式绑定的技巧是您希望能够将特定于元素的参数传递给处理程序(“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". “elementData”变量将最终(在这种情况下,无论如何)是一个包含两个值的数组,“data1”和“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. 您可以将JSON符号值赋予“data-foo”属性,当您使用jQuery“.data()”方法获取属性时,它将自动为您解码JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM