老师麻烦问下问题

来源:3-4 自由编程

vivi_li

2020-06-17 13:52:24

通过动态生成插入的元素,绑定事件的话是否必须在动态生成的事件中进行绑定?我试了下如果在外面绑定事件好像没办法绑上

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <style>
       .container{
           width: 200px;
           height: 200px;
           background-color: pink;
       }
       .smallbox{
           width: 100px;
           height:100px;
           background-color: blue;
       }
   </style>
</head>
<body>
   <button id="btn">点击这里!</button>
   <div class="container"></div>
</body>
<script src="https://cdn.bootcss.com/zepto/1.1.7/zepto.min.js"></script>
<script>
   $('#btn').on('click',function () {
       $('.container').append('<div class="smallbox">我是smallbox内容</div>')
       console.log($(".smallbox"))
       $(".smallbox").on('click',function () {
           alert('已执行')
       })
   });

   // $('.container').on('click',function (e) {
   //     if($(e.target).hasClass('smallbox')){
   //         alert('已执行')
   //     }
   // })

</script>
</html>

写回答

1回答

好帮手慕久久

2020-06-17

同学你好,可以通过事件委托的方式,将事件绑定在父元素,从而实现为每一个新建的子元素都添加事件,如下:

http://img.mukewang.com/climg/5ee9c3f90971aa0811570448.jpg

如果我的回答帮到了你,欢迎采纳,祝学习愉快!

0

0 学习 · 6815 问题

查看课程