jQuery防止重复提交的方法

本文介绍了如何使用jQuery为带有特定类的链接添加点击事件处理程序,并解释了如何避免重复添加事件导致的问题。同时,讨论了如何在回调函数中正确传递额外参数的方法。
function addClickHandlers() {
   $("a.remote", this).click(function() {
     $("#target").load(this.href, addClickHandlers);
   });
 }
 $(document).ready(addClickHandlers);

解释:


Now addClickHandlers is called once when the DOM is ready and then everytime when a user clicked a link with the classremote and the content has finished loading.

Note the $("a.remote", this) query, this is passed as a context: For the document ready event,this refers to the document, and it therefore searches the entire document for anchors with class remote. WhenaddClickHandlers is used as a callback for load(), this refers to a different element: In the example, the element with id target. This prevents that the click event is applied again and again to the same links, causing a crash eventually.


Another common problem with callbacks are parameters. You have specified your callback but need to pass an extra parameter. The easiest way to achieve this is to wrap the callback inside another function:

// get some data
 var foobar = ...;
 
 // specify handler, it needs data as a paramter
 function handler(data) {
   //...
 }
 
 // add click handler and pass foobar!
 $('a').click(function() {
   handler(foobar);
 });
 
 // if you need the context of the original handler, use apply:
 $('a').click(function() {
   handler.apply(this, [foobar]);
 });


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值