2011-11-25 19 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发现最接近的父匹配选择器,所以在这种情况下,它是该元素所在的表