2011-04-25 80 views
0

我有一個插件,實質上是對服務器端的表進行排序,並將內容放回到容器中。我有一個綁定函數,它將一個單擊事件添加到表格單元格中,以調用父表單提交。我覺得這不是解決這個問題的最好方法。有任何想法嗎?jQuery:有一個更有效的方法來做到這一點,不是嗎?

$.fn.myplugin = function() { 
    return this.each(function() { 
    var parentform = $(this).parents("form"); 
    var tableidentifier = $(this).attr("id"); 

    var bindclicks = function() { 
     parentform.find("table#" + tableidentifier + " thead tr th").click(function() { 
     // Some code to change the sort column- boring! 
     parentform.submit(); 
     }); 
    } 

    bindclicks(); 

    parentform.submit(function() { 
     $.post(parentform.attr("action"), parentform.serialize(), function(res) { 
     parentform.find("table#" + tableidentifier).replaceWith($(res)); 
     bindclicks(); 
     }) 
     return false; 
    }); 
    }); 
} 

我首先調用bindclicks()函數來設置單擊處理了,然後因爲我做replaceWith()我再次調用它來重新綁定的事件。它的工作原理,但我很好奇..

回答

3

您可以使用.delegate(),因此您無需每次重新綁定您的點擊處理程序。

$.fn.myplugin = function() { 
    return this.each(function() { 
     var parentform = $(this).parents("form"); 
     var tableidentifier = $(this).attr("id"); 

     parentform.delegate("table#" + tableidentifier + " thead tr th", "click", function() { 
      parentform.submit(); 
     }); 

     parentform.submit(function() { 
      $.post(parentform.attr("action"), parentform.serialize(), function(res) { 
       parentform.find("table#" + tableidentifier).replaceWith($(res)); 
      }) 
      return false; 
     }); 
    }); 
} 

只用剪斷,它表示,這應該工作,因爲要更換<table/>和委派的事件被綁定到<form/>

+0

+1,'代表'是要走的路 – 2011-04-25 19:11:32

+0

酷!從來沒有使用委託功能 - 非常非常方便。 – Wells 2011-04-25 19:15:30

0

的這個代替:

var bindclicks = function() { 
     parentform.find("table#" + tableidentifier + " thead tr th").click(function() { 
      parentform.submit(); 
     }); 
    } 

    bindclicks(); 

試試這個:

$("table#" + tableidentifier + " thead tr th", parentForm) 
    .bind('click', function() { 
     parentForm.submit(); 
    }); 

如果使用live而不是bind,它會綁定單擊處理到任何新創建的元素。

+0

就沒有我需要張貼同樣的代碼在'$表單提交後的.post'回調? – Wells 2011-04-25 19:05:00

相關問題