javascript - 为什么添加后的行,删除和增加按钮点击都没有反应
巴扎黑
巴扎黑 2017-04-10 17:15:23
0
6
217
<!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>
                    <p 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>
                    </p>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>
<script>
    $(".glyphicon-trash").click(function(){
       $(this).parents("tr").remove();
    });
  
    $(".glyphicon-plus").click(function() {
        var flotr='<tr><td><p 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></p></td></tr>'
     $(flotr).appendTo(".business_setboxc_01");   
});

</script>
巴扎黑
巴扎黑

全部回覆(6)
洪涛

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

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

});

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

 //do something

});

PHPzhong

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

PHPzhong
$(".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() { });
Peter_Zhu

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

洪涛

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

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

小葫芦

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板