2009-06-11 19 views
0

我正在嘗試爲表格寫jquery-plugin。jQuery動態表格直播點擊插件

我有一個從服務器2個動態表:

(function($) { 
 
    $.fn.smplPlugin = function() { 
 
     return this.each(function() { \t \t 
 
     $this = $(this); 
 
     $this.find("td").live('click', function() { 
 
      alert($this.attr('id') +" "+ $(this).parent().attr('id')); 
 
     }); 
 
     }); 
 
    }; 
 

 
    $(document).ready(function() { 
 
     $("#first_column").smplPlugin(); 
 
     $("#second_column").smplPlugin(); 
 
    }); 
 

 
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> 
 
<div id="first_column"> 
 
    <table> 
 
    <tr id="f1"> 
 
     <td class="select">some text</td> 
 
     <td class="name">some name</td> 
 
    </tr> 
 
    <tr id="f2"> 
 
<!-- 
 
     .... 
 
     more same rows 
 
     .... 
 
--> 
 
    </tr> 
 
    </table> 
 
</div> 
 

 
<div id="second_column"> 
 
    <table> 
 
    <tr id="s1"> 
 
     <td class="select">some text</td> 
 
     <td class="name">some name</td> 
 
    </tr> 
 
    <tr id="s2"> 
 
<!-- 
 
     .... 
 
     more same rows with differents id's 
 
     .... 
 
--> 
 
    </tr> 
 
    </table> 
 
</div>

然後我想在<td>添加click事件。

當我<td>點擊第一個或第二個表,我總是得到同樣的,最後一個對象ID,它是:是second_column,但不同的第一或第二排的ID

點擊[第一列] [TR ID = F1] [TD類=名]輸出second_class F1

點擊[第二塔] [TR ID = S2] [TD類=選擇]輸出second_class S2

等。 任何想法?

+1

從jQuery 1.7起,.live()已被棄用.on()請參閱http://api.jquery.com/on/ – bpeterson76 2011-12-09 20:33:34

回答

0

試試這個

(function($) { 
    $.fn.smplPlugin = function() { 
    $("td",this).live('click', function() { 
     alert($(this).parent().attr('id') +" "+ $(this).parents('div').attr('id'));   
    }); 
    }; 
})(jQuery); 
1

你行$this = $(this);必須是var $this = $(this);

前者創建一個名爲$this的全局變量,並在每個循環的每次迭代中分配一個新的值/引用 - 使用變量總是指向最後一個迭代元素。後面的代碼在循環體的閉包中創建一個變量 - 從而爲每個點擊處理程序提供對其行的引用。