码迷,mamicode.com
首页 > Web开发 > 详细

jQuery动态添加的节点事件无法触发

时间:2017-08-29 23:43:18      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:https   col   UI   添加   com   父类   cli   解决   无法   

添加节点之前如图:

技术分享

点击图中的 "第一个" 之后会触发click事件,效果如图:

技术分享

 

点击按钮的之后,添加节点之后如图:

技术分享

这时点击图中的 "第一个",却不会触发click事件。

此时代码如下: 

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
<head>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
    $(function(){
        $(".a1").on("click",function(){
            alert("触发a标签的点击事件!");
        });    
    });
    
    function cl(){
        $(".div2").html(<a class="a1">第一个</a><br><a class="a2">第二个</a>);
    }
</script>
</head>
<body>
    <div class="div1">
        <div class="div2">
            <a class="a1">第一个</a>
            
        </div>
        <input onclick="cl()" type="button" value="添加节点"/>
    </div>
</body>
</html>

以上问题可以通过绑定几种方法解决

1.是直接在添加标签的时候添加一个onclick事件;

2.通过绑定这个标签的父类或者body来达到激活click事件的效果。

改过之后的代码如下:

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
<head>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
    $(function(){
        /*$(".a1").on("click",function(){
            alert("触发a标签的点击事件!");
        });*/    
        
        /*$(".div1").on("click",".a1",function(){
            alert("触发a标签的点击事件!");
        });*/
        
        $(".div2").on("click",".a1",function(){
            alert("触发a标签的点击事件!");
        });
        
        /*$("body").on("click",".a1",function(){
            alert("触发a标签的点击事件!");
        });*/
    });
    
    function cl(){
        $(".div2").html(<a class="a1">第一个</a><br><a class="a2">第二个</a>);
    }
</script>
</head>
<body>
    <div class="div1">
        <div class="div2">
            <a class="a1">第一个</a>
            
        </div>
        <input onclick="cl()" type="button" value="添加节点"/>
    </div>
</body>
</html>

如果出现,点击一次,出现两次click事件的话,

考虑使用propagation()方法处理冒泡。

jQuery动态添加的节点事件无法触发

标签:https   col   UI   添加   com   父类   cli   解决   无法   

原文地址:http://www.cnblogs.com/GoneLW/p/7450768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!