为什么添加后的行,删除和增加按钮点击都没有反应

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    <title>demo about table</title>
</head>

<body>
    <br/>
    <table class="business_setboxc_01">
        <thead>轻货阶梯价格</thead>
        <tbody>
            <tr>
                <td>
                    <div class="form-group"> 超过&nbsp;
                        <input type="text" placeholder="1" size="5" class="form-control sel_add_01">&nbsp;公斤,
                        <input type="text" size="5" class="form-control sel_add_01">&nbsp;元/公斤&nbsp;&nbsp;<span class="glyphicon glyphicon-plus">增加</span>&nbsp;<span class="glyphicon glyphicon-trash">删除</span>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>
<script>
    $(".glyphicon-trash").click(function(){
       $(this).parents("tr").remove();
    });
  
    $(".glyphicon-plus").click(function() {
        var flotr='<tr><td><div class="form-group"> 超过&nbsp;<input type="text" placeholder="1" size="5" class="form-control input-smsel_add_01">&nbsp;公斤,<input type="text" size="5"  class="form-control sel_add_01">&nbsp;元/公斤&nbsp;&nbsp;<span class="glyphicon glyphicon-plus">增加</span>&nbsp;<span class="glyphicon glyphicon-trash">删除</span></div></td></tr>'
     $(flotr).appendTo(".business_setboxc_01");   
});

</script>
阅读 4.1k
6 个回答

$(document).on('click','.glyphicon-trash',function(){

$(this).parents("tr").remove();

});

$(document).on('click','.glyphicon-plus',function(){

 //do something

});

因为你在绑定删除事件的时候,那些新增的行还不存在,所以没有绑上删除事件。。你可以使用delegate进行绑定,百度或者google的用法即可。

$(".glyphicon-trash").click(function () { });
$(".glyphicon-plus").click(function() { });

这两句话发生作用的时候你新增加的按钮都还没得,所以 $(selector) 并没有选中后来添加的节点。
这种情况可以使用父结节代理事件的方式解决

$("table.business_setboxc_01").on("click", ".glyphicon-trash", function() { });
$("table.business_setboxc_01").on("click", ".glyphicon-plus", function() { });

因为你只给最开始就存在的按钮绑定了点击事件,用事件代理吧,点击事件绑到父级元素上。

因为$(".glyphicon-plus").click(function() {})是注册给当时的dom元素的, 新加的元素没有.

你可以每次新加元素时加上同样的事件, 或者在table元素上加event delegate

你的script标签,放哪里了???放在</body>之前。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题