从表中删除产品

时间:2014-06-16 20:31:59

标签: javascript jquery html

我想从表中删除产品行,如何将其添加到要添加的元素中?

这里是我的小提琴:http://jsfiddle.net/YgQ7y/

HTML:

<select name="produtos" id="lista_produtos">
    <option value="selecione...">Selecione...</option>
    <option value="value 1">value 1</option>
    <option value="value 2">value 2</option>
    <option value="value 3">value 3</option>
</select>
<input type="text" id="quant_produtos" name="amount" placeholder="Quant">
<button id="add_produto">add product</button>
<br><br>
<table border="1" width="100%" id="cesta_produtos">
    <thead>
        <tr>
            <td>name:</td>
            <td>quant:</td>
            <td>remove</td>
        </tr>
    </thead>
    <tbody></tbody>
</table>

JS:

$('#add_produto').on('click', function () {

    var $table = $('#cesta_produtos tbody'), // Product Table

        $list = $('#lista_produtos').val(), // Select with products

        $quant = $('#quant_produtos').val(), // Quantity field

        $remove = "<a href='#' class='del_produto'>x</a>"; // Link to remove product

    // Insert the product inside the table
    $table.append("<tr><td>" + $list + "</td><td>" + $quant + "</td><td>" + $remove + "</td></tr>");

});

2 个答案:

答案 0 :(得分:4)

JSFiddle:http://jsfiddle.net/TrueBlueAussie/YgQ7y/1/

$(document).on('click', '.del_produto', function(){
  $(this).closest('tr').remove();
});

这使用委托事件处理程序。基本上它会倾听任何“点击”消息。事件冒泡到文档,然后它应用jQuery选择器,然后它将函数应用于生成事件的任何匹配元素。

优点是双重的。首先,事件发生之前不需要存在项目,但仍然可以找到,其次,这意味着单个事件处理程序处理任意数量的项目(如果单个事件处理程序附加到单个元素,则处理很多项目。)

准则:

您通常会在动态元素的第一个不变的祖先(也许是您的表格元素#cesta_produtos)中侦听委派事件。如果一个不可用/方便,请使用文档(不要使用$('body'),因为某些事件类型有一些奇怪的副作用,包括点击)。

e.g。

$('#cesta_produtos').on('click', '.del_produto', function(){
  $(this).closest('tr').remove();
});

注意:由于您的链接是href =&#34;#&#34;您需要停止默认操作,否则当您单击删除&#34; x&#34;时,长页面将滚动到顶部。只需从点击处理程序返回false,或在事件参数上使用preventDefault()

$(document).on('click', '.del_produto', function(){
   $(this).closest('tr').remove();
   return false;
});

$(document).on('click', '.del_produto', function(e){
  e.preventDefault();
  $(this).closest('tr').remove();
});

答案 1 :(得分:1)

我已更新您的fiddle

您需要使用.on jQuery方法并委派事件:

$('#cesta_produtos').on('click', '.del_produto', function(e){
    e.preventDefault();
    $(this).closest('tr').remove()
})