2012-02-04 70 views
0

我將jQuery和dataTables插件一起使用。 dataTables提供了打開和關閉行的功能(意味着可以在常規行下打開附加信息行)。jQuery HTMLElement打包/解包

http://datatables.net/api我得到了下面的良好工作示例:

$(document).ready(function() { 
    var oTable; 

    // 'open' an information row when a row is clicked on 
    $('#example tbody tr').click(function() { 
     if (oTable.fnIsOpen(this)) { 
      oTable.fnClose(this); 
     } else { 
      oTable.fnOpen(this, "Temporary row opened", "info_row"); 
     } 
    }); 

    oTable = $('#example').dataTable(); 
}); 

現在我想不添加單擊處理程序到整個行,但該行的元素:

$("#openCompliantsTable .icon-comment").click(… 

但當然this現在不是指tr元素,而是指某個子元素。我嘗試更改代碼是將this替換爲$(this).parent().parent().get(),但沒有成功。

後來我發現,其實this似乎不是一樣$(this).get(),即使雙方都[object HTMLElement]對象,這讓我吃驚。

任何可能的結果?

編輯: 我的HTML表看起來像這樣:

<table id="openCompliantsTable" class="table table-striped table-bordered table-condensed"> 
    <thead> 
     <tr> 
     <th>Reklamationsnummer</th> 
     <th>Reklapositionsnummer</th> 
     ... 
     <th>Status</th> 
     <th>Aktion</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
     <td>1</td> 
     <td>1</td> 
     ... 
     <td>offen</td> 
     <td><i class="icon-ok"></i><i class="icon-trash"></i><i class="icon-flag"></i><i class="icon-comment"></i></td> 
     </tr> 
     ... 
    </tbody> 
    </table> 
+0

你確定'$(this).parent()。parent()'找到TR元素嗎? – 2012-02-04 09:50:53

+0

是的,我可以添加一些CSS類。 – thorink 2012-02-04 09:55:05

回答

1

.get()不帶參數返回陣列與所有的匹配元素的所有的DOM元素。即使你只有一個匹配的元素,你也會得到一個包含一個項目的數組。

使用索引,.get()將檢索單個元素,這是您之後的操作。

你必須使用:

$(this).parent().parent().get(0) 
+0

謝謝,就是這樣! – thorink 2012-02-04 10:02:56

2

更換

$(this).parent().parent().get() 

$(this).parent().parent().get(0) 

你的功能可能是:

$('#openCompliantsTable .icon-comment').click(function() { 
    var tr = $(this).parent().parent().get(0); 
    if (oTable.fnIsOpen(tr)) { 
     oTable.fnClose(tr); 
    } else { 
     oTable.fnOpen(tr, "Temporary row opened", "info_row"); 
    } 
}); 

另請參閱this example

0

或更短:

$(this).parents('tr')[0]; 

這需要的第一個父是「TR」,築巢沒關係,你不必在乎你有多少級加緊。如果你有嵌套表格,請小心。