为社么无法alert?

来源:3-4 自由编程

慕侠9181480

2019-09-12 09:33:53

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

    <style>

        .pinkBox{

            width: 300px;

            height: 300px;

            background-color: pink;

        }

        .smallBox{

            width: 100px;

            height: 100px;

            background-color: aqua

        }

    </style>

</head>

<body>

    <button type="button">点击这里</button>

    <div class="pinkBox">

        <!-- <div class="smallBox">我是<br>smallBox<br>内容</div> -->

    </div>


    <script src="https://cdn.bootcss.com/zepto/1.1.7/zepto.min.js"></script>

    <script>

        var $text = $('<div class="smallBox">我是<br>smallBox<br>内容</div>')

        $("button").click(function(){

            $(".pinkBox").append($text)

        })


        $(".smallBox").click(function(){

            alert('已执行');

        })

    </script>

</body>

</html>



写回答

1回答

好帮手慕慕子

2019-09-12

同学你好, 因为代码是从上到下执行, 但是按钮绑定事件是在被点击的时候才触发。所以在代码开始按着顺序执行的时候, 此时还没有将smallBox添加到页面中, $('.smallBox')无法获取到对应的元素, 导致最终不会弹出窗口

建议修改: 可以在button点击事件内部, 确定将内容追加到页面中,之后,再给smallBox绑定事件

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

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

如果帮助到了你, 欢迎采纳!

祝学习愉快~~~

0

0 学习 · 6815 问题

查看课程