2012-12-27 135 views
0

我有一個表,並希望添加一個ajax加載在我點擊鼠標的行下面。但是,我不知道如何獲得索引,而是將它追加到最後。如何在選定的<tr>下添加<tr>?

例如點擊「hol」並將該行插入「hol」行下方。

請參閱--> fiddle <--

<table id="tab_open_deals" class="table table-condensed table-striped cb_table-hover"> 
    <thead> 
    <tr> 
     <th>A</th> 
     <th>B</th> 
     <th>C</th> 
    </tr> 
    </thead> 
    <tbody id="search_result"> 
    <tr> 
     <td>Lunch Deal- Light</td> 
     <td>39.90</td> 
     <td>29 Dec 2012</td> 
    </tr> 
    <tr> 
    <td>hol</td> 
    <td>1499.00</td> 
    <td>8 Jan 2013</td> 
    </tr> 
</tbody> 
</table> 


$(document).ready(function() { 
    $('#tab_open_deals tbody tr').off('click').on('click', function() { 
     var row = $('<tr/>'); 
     $(row).load('/echo/html/', { 
      html: '<td class="override" colspan="4"><table class="table-striped sub_table-hover"><thead><tr><th>Sub1</th><th>Sub2</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></tbody></table></td>' 
     }); 

     $(this).parent().append(row); 
    }); 
}); 
+0

或許'$()。after或$()。insertAfter'就是你要找的 –

回答

1

在您的函數的情況下,id或指數,是無關緊要;簡單地使用當前點擊tr參考:

row.insertAfter($(this)); 

JS Fiddle demo

順便說一句,row已經一個jQuery對象(因爲你創造了它:row = $('<tr />')),所以你不需要包裝在一個jQuery對象中的下一行$(row).load(/*...*/),只需使用:row.load(/*...*/)

參考:

3

你不需要索引,剛剛獲得的點擊trclosest好爲),並使用after參考:

$('#tab_open_deals tbody tr').off('click').on('click', function() { 
    var row = $('<tr/>'); 
    $(row).load('/echo/html/', { 
     html: '<td class="override" colspan="4"><table class="table-striped sub_table-hover"><thead><tr><th>Sub1</th><th>Sub2</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></tbody></table></td>' 
    }); 

    $(this).closest("tr").after(row); 
}); 

但您掛鉤事件的方式,它不會掛在您添加的任何新行上。您可能會考慮delegate,這是用於做事件委託(您也可以使用超重on函數在新版本的jQuery中進行事件委託)。

這裏有一個簡單的例子:

$("#theTable tbody").delegate("tr", "click", function() { 
    var row = $("<tr><td></td></tr>"); 

    row.find("td").text("New row at " + new Date()); 

    $(this).after(row); 
}); 

Live Example | Source

或者如果你喜歡ondelegate,改變

$("#theTable tbody").delegate("tr", "click", function() { 

$("#theTable tbody").on("click", "tr", function() { 

(注意參數的順序改變。)Live Example | Source


旁註:

  • 您可能要等到加載內容,但是,通過不把它在DOM直到load回調火災。

  • ,你發送HTML片段服務器這似乎很奇怪(這是第二個參數load呢,如果它不是一個函數)。但是,鑑於您要發送到的URL的名稱,我假設它是正確的。 :-)

+0

Thanks :) +1 from me。我認爲其他答案更好,因爲已經有了對tr的引用,因此'.closest('tr')'實際上不是必需的。關於這個怪異的加載url,它只是一個回聲來模擬jsfiddle上的ajax。那是我知道的唯一方法。 ;) – Houman

+0

@Kave:使用'closest'是無害的和靈活的。但是,是的,如果你設置你的事件處理程序,使得'this'是'tr',你不需要'最接近'(事實上,我在我的實例中展示了'delegate'和'on'調用)。同樣,你現在連接你的行的方式意味着* new *行不會被連接起來,而對於上面的例子,它們會。 –

相關問題