jq给动态添加的元素绑定事件

现在不用了live

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src=js/jquery-3.3.1.min.js></script>

</head>

<body>
    <div class="box">
        <button>click</button>
        <p>1</p>
        <p>1</p>
    </div>
</body>

</html>

<script>
    $(function () {
    
    
        $('.box').click(function () {
    
    
            $('p').after('<p>new</p>')
        })
        $('.box').on('click', 'p', function (e) {
    
    
            e.stopPropagation()
            console.log($(this));
        })
    })
</script>

注意事项。
$(’.box’).on()
中的.box 不一定是直系父元素(我试过直系父元素不能绑定)。也可以是任意祖先。

猜你喜欢

转载自blog.csdn.net/work33/article/details/121210339