事件代理on

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>on</title>
</head>
<body>
<input type="text"><input type="button" value="添加">
<ul>

</ul>
<script src="js/jQuery3.3.1.js"> </script>
<script>

    $(function () {
        $("ul").on("click", "li", function () {  //事件代理
           console.log($(this).text())    //记住$ 取当前值
        });

        $("input[type=button]").click(function () {
            let txt = $("input[type=text]").val();    //input取值用val
            $(`<li>${txt}</li>`).appendTo("ul");
            })
        
         //未来追加的元素  是没有事件 我们通过事件委托  当你出现点击页面中的DOM没有任何反应
        //1.DOM是否underfine  2.考虑事件代理
    })
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/tcpblog/p/9965968.html