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]);
 });


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章