jQuery绑定事件与解除绑定

340 阅读1分钟
<!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>
</head>

<body>
    <button class="a">点我</button>
    <!-- <button class="b">接触btn的点击事件</button> -->
    <div style="display:none;width: 100px;height: 100px;background: red;"></div>
    <script src="./jquery-1.12.4.js"></script>
    <script>


        /* toggle()方法不带参数,与show( )和hide( )方法作用一样
 */
        /* hover里面只有一个方法的时候,移入移出都执行这个方法 */
        $('.a').hover(function(){
           $('div').toggle();
        })



        /* 老版本 */
        // $('button').bind('click', function () {
        //     alert('我爱打游戏')
        // })
        // $('button').mouseover(function () {
        //     $('div').show()
        // })
        // $('button').mouseout(function () {
        //     $('div').hide()
        // })
        /* 一个元素可以绑定多个事件 */
        // $('.a').bind({
        //     click:function(){
        //         alert('我爱打游戏')
        //     },
        //     mouseover:function(){
        //         $('div').show()
        //     },
        //     mouseout:function(){
        //         $('div').hide()
        //     }
        // })
        // $('.b').click(function(){
        //     // $('.a').unbind('click')
        //     // alert('解绑了a的点击事件')
        //     /* 如果不加参数,就是默认清除所有的绑定事件 */
        //     $('.a').unbind()
        // })
        /* 新版本 */
        /* 正常绑定多个事件,可以使用对象的方式 */
        // $('.a').on({
        //     click:function(){
        //         alert('我爱打游戏')
        //     },
        //     mouseover:function(){
        //         $('div').show()
        //     },
        //     mouseout:function(){
        //         $('div').hide()
        //     }
        // })
        // $('.b').click(function(){
        //     $('.a').off()
        // })
        /* 在未来的元素上加事件是无效的 */
        // $('h3').click(function(){
        //     alert('你好')
        // })

        /* 因为未来元素是暂时不存在,所以我可以把事件给已存在的父元素
        等未来元素出现了,我再给你绑定上 */
        /* $('body').on('click','h3',function(){
            alert('你好')
        }) */
        /* bind给未来元素加事件,会存在问题,所以后面使用on来绑定 */
        // $('body').bind('click','h3',function(){
        //     alert('你好')
        // })


        /* on 方法通常有三个参数 */
        /* 给未来元素添加事件的时候
        事件类型,未来元素,绑定的事件
        */
        /* 正常的绑定,两个参数,第一个是事件类型,第二个是绑定的事件方法 */

        // $('.a').on('click', function () {
        //     $(this).after('<h3>我是新加的元素</h3>')
        // })
        /* 给未来元素绑定多个事件 */
        // $('body').on('click','h3',function(){
        //     console.log('你好')
        // })
        // $('body').on('mouseover','h3',function(){
        //     console.log('你好 德玛西亚')
        // })



    </script>
</body>

</html>