删除按钮上的行单击

时间:2012-01-27 01:21:38

标签: javascript jquery html

尝试使用“减去”按钮删除单击的行。

“添加”按钮运行良好。

HTML:

<table id="mytable" width="250px" border="0" cellspacing="0" cellpadding="0"  style="text-align:center;>
   <thead>
   <tr class="product">
   <th style="text-align:center;"><strong>Item</strong></th>
   <th style="text-align:center;"><strong>Qty.</strong></th>
   <th style="text-align:center;"><strong>Remarks</strong></th>
   </tr>
   </thead>
   <tr name="product" class="product">
   <td width="100px"><input type="text" width="100px" name="product" id="product" /></td>
   <td width="5px"><input type="text" width="5px" size="1" maxlength="2" name="qty" id="qty" /></td>
   <td width="100px"><input type="text" width="100px" height="14px" name="remarks" id="remarks" /></td>
   <td><input type="submit" name="add" id="add" value="+" /></td>
   <td><input type="submit" name="subtract" id="subtract" value="-" /></td>
   </tr>
   </table>

我正在使用的是什么:

<script type="text/javascript">
$(document).ready(function() {
    $("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #product').val('');
    $('#mytable tbody>tr:last #qty').val('');
        $('#mytable tbody>tr:last #remarks').val('');
            $('#mytable tbody>tr:last #add').val('+');
return false;
    });
});

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

您不能在页面上多次使用相同的ID .. 因此,如果每行都有一个删除该行的按钮,您可能希望使用类名来定位该元素。 因此我建议切换到这样的类:

<td><input type="submit" name="subtract" class="subtract" value="-" /></td>

然后在JS

$("input.subtract").click(function() {
 $(this).closest("tr").remove();    
});

您还需要修复添加按钮,因为如果您有多行,则会有重复的ID

答案 1 :(得分:0)

$("#subtract").click(function(e){
    $(this).closest(".product").remove();
    e.preventDefault();
});

我还建议使用类而不是id进行减法和添加,因为你在dom中会有多个副本,并且认为重复ID是不礼貌的。

答案 2 :(得分:0)

与Matt的代码类似,这也有效:

$("input.subtract").click(function() {
 $(this).parents("tr").remove();    
});

我不知道一个是否比另一个好,但我可以确认这个代码有效。