JqueryOn绑定事件方法介绍

JqueryOn绑定事件方法介绍

 

1. 简介javascript

(1) On()方法在被选及子元素上添加一个或多个事件处理程序css

(2) 在jquery 版本1.7起,on()方法是bind(),live()和delegate()方法的新的替代品,该方法给API带来不少便利,简化了JQUERY代码库。html

(3) 使用on()方法添加的事件处理程序适用于当前及将来的元素(好比由脚本建立的新元素)java

2. 目前了解到使用场景jquery

(1) 使用ajax请求数据时使用。ajax

(2) 对加载完页面以后的元素进行事件绑定。app

3. 注意事项测试

(1) 你使用jquery追加的元素要在一个不会进行改变的父级之下,能够是DOCUMENT。this

(2) 绑定有两种方式spa

① 单个事件绑定

1) $(“#id”).on(‘click’,function(){})    把点击事件绑定到id为id的元素身上

2) $(“#id”).on(‘click’,’.div’,function(){})  把点击事件绑定到id为id的子级元素类名为div的元素身上

② 多事件同时绑定到一个元素上

③ $(“.div”).on({

mouseover:function(){$(“body”).css(“background-color”,”red”)},

mouseout:function(){$(“body”).css(“background-color”,”yellow”);},

click:function(){$(“body”).css(“background-color”,”green”)}

})

4. 案例

<div  class="entrust">
    <button class="btn_class"> 测试 </button>
    <button class="b_class"> 测试_测试 </button>
    <div>
        <button class="btn_id"> 测试1 </button>
        <button class="b_id"> 测试_测试1 </button>
    </div>
</div>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>ENTRUST</title>
</head>
<body>
<div>
    <button> 测试 </button>
    <button> 测试-测试-测试 </button>
    <div>
        <button> 测试1 </button>
        <button> 测试-测试ButtonA </button>
    </div>
</div>

<script type="text/javascript" src="/js/jquery-1.8.3.js"></script>
<script>
    $(".onCase").on("click",".onCaseButtonA",function(){
        console.log(this.class,"测试—class-onCaseButtonA");
    });
    $('.onCaseButton').click(function () {
        console.log(this.class,"测试—class-onCaseButton")
    });
    $('.Button').click(function () {
        $('<button> 测试-Button </button>').append();
    });
    $('.ButtonA').click(function () {
        $("<button> 测试-测试ButtonA </button>").append();
    });
</script>
</body>

</html>

相关文章
相关标签/搜索