2011-11-25 20 views
0

這裏的情況:jquery添加行只爲點擊表按鈕

我正在使用jquery插件來添加表中的行。該表的頂部有(+)按鈕。如果我點擊(+)按鈕,它將直接向表中添加1行。 當我在頁面中使用1個表格時,它運行完美。但是,如果我使用2個或更多的表格,當我點擊(+)按鈕時,所有表格(不僅僅是我剛剛點擊的表格)也添加了1行。當我檢查的.js代碼中添加該行:

var tabularInput = $(this); 
$(settings.addInput).click(function(event) { 
     if(settings.limit == 0 || tabularInput.find("tbody > tr").length < settings.limit) { 
      if(settings.beforeAdd == null || settings.beforeAdd(tabularInput)) { 
       var tbody = tabularInput.find("tbody"); 

       alert(tabularInput.id); 

       var newRow = $(settings.rowTemplate).clone(); 
       tbody.append(newRow); 

       newRow.find(":input").each(function() { 
        $(this) 
         .attr("id", $(this).attr("id").replace(/\___template__\_/, "_" + rowCount + "_")) 
         .attr("name", $(this).attr("name").replace(/\[__template__\]/, "[" + rowCount + "]")); 
       }); 

       tabularInput.find(settings.removeInput).show(); 
       if(settings.limit != 0 && tabularInput.find("tbody > tr").length >= settings.limit) { 
        tabularInput.find(settings.addInput).hide(); 
       } 

       rowCount++; 
       if(settings.afterAdd) settings.afterAdd(tabularInput, newRow); 
      } 
     } 
     event.preventDefault(); 
    }); 

伊夫添加的警報(tabularInput.id)代碼,看看標識,但它說不確定。 現在,這裏是HTML表:

<table class="jtabularinput" id="yw0"> 
<thead> 
    <th>Nama Depan</th> 
    <th>Nama Tengah</th> 
    <th>Nama Belakang</th> 
    <th><a class="input-add" title="Click to add a new row" href="#">Add</a></th> 
</thead> 
<tbody> 
    <tr> 
    <td><input name="Pengarang[0][nama_depan]" id="Pengarang_0_nama_depan" type="text" maxlength="16" /></td> 
    <td><input name="Pengarang[0][nama_tengah]" id="Pengarang_0_nama_tengah" type="text" maxlength="16" /></td> 
    <td><input name="Pengarang[0][nama_belakang]" id="Pengarang_0_nama_belakang" type="text" maxlength="16" /></td> 
    <td style="text-align:center"> 
    <a class="input-remove" title="Click to remove this row" href="#">Remove</a> 
    </td> 
    </tr> 
    </tbody> 
</table> 

任何人有地方出了問題的解決方案或見解?非常感謝

EDITED

發現錯誤在哪裏。我改變:

​​

是:

tabularInput.find(settings.addInput).click(function(event) {..} 

這種方式只需要相應的表格,並添加其行。現在它運作完美。感謝所有提出的解決方案和你的關懷,以幫助我解決問題=)

+0

jsfiddle中的完整示例或者有所幫助。另外,你想提醒(tabularInput.attr('id')) –

+0

var tabularInput = $(this);''範圍是什麼?這是一個窗口對象嗎? –

+0

你定義了'+'按鈕還是創建它?是「+」按鈕是桌子還是兄弟姐妹的孩子? –

回答

0

tabularInput是一個jquery包裝對象,如果你想要它的ID,你需要或者問問jquery或者下降到dom元素本身:

1)tabularInput.attr('id')

2)tabularInput[0].id

有比這個插件的幾個問題多,但你重複是由於範圍誤解。你不能指望所有這些事件處理程序記住你執行插件時定義的某個緩存對象,除非你將它作爲參數傳遞給它的閉包。

快速修復:

$(settings.addInput).click(function(event) { 
    var tabularInput = $(this).closest('table'); 
0

試試這個

$(settings.addInput).click(function(event) { 
    var tabularInput = $(this).closest('table.jtabularinput'); 
    // then the rest... 

$(這)是 'addInput' 項目(當從單擊處理程序中調用)

.closest發現最接近的父匹配選擇器,所以在這種情況下,它是該元素所在的表