31-事件处理

134 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件</title>
</head>
<body>
    <ul>
        <li>111</li>
        <li>222</li>
        <li>333</li>
        <li>444</li>
    </ul>
    <button>add</button>
</body>
<script src="jquery-3.1.1.js"></script>
<script>
    //处理加载不出来的问题
    /*$(document).read(function () {
        
    });*/
    //另一种方式
    $(function () {
        
    })
    //绑定事件
    /*$("ul li").click(function () {
        alert("666");
    });*/
    /*$("ul li").bind("click",function () {
        alert("666");
    });*/
    //事件委托(解决动态添加时的点击事件)
    $("ul").on("click","li",function () {
        alert("999")
    })
    $("button").click(function () {
        var $ele = $("<li>");
        var len = $("ul li").length;
        $ele.html(len+1);
        $("ul").append($ele);
    })
</script>
</html>

自定义方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>111</p>
    <p>222</p>
    <p>333</p>
    <script src="jquery-3.1.1.js"></script>

    <script>
        //自定义方法
        $.extend({
            Mymethod:function () {
                console.log("fengfeng");
            }
        })
        $.Mymethod();

        $.fn.extend({
            GetText:function () {
                console.log($(this).html());
            }
        })
        $("p").GetText();
    </script>

</body>
</html>