jquery自定义事件例子

jquery自定义文档说明:###

http://www.css88.com/jqapi-1.9/on/
http://www.css88.com/jqapi-1.9/trigger/
http://www.css88.com/jqapi-1.9/off/

例子:
<pre>
<!DOCTYPE html>
<html>
<head>
<style>
button {
margin: 5px;
}

button#theone {
    color: red;
    background: yellow;
}
</style>
<script src="http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {


    $(document).on('smile', function() {
        console.log("is smile event")
    });

    $(document).trigger('smile');


    $(document).on('customEvent', function() {
        return 'hello world!';
    });

    var event = $.Event('customEvent');
    $(document).trigger(event);

    console.log(event.result);


    $("#btn").bind("myClick", function(event, message1, message2) { //获取数据
        $("#test").append("<p>" + message1 + message2 + "</p>");
    });
    $("#btn").trigger("myClick", ["我的自定义", "事件"]); //传递两个数据


    $('#foo').on('custom', function(event, param1, param2) {
        alert(param1 + "\n" + param2);
    });

    $('#foo').on('custom', function(event, param1, param2) {
        alert("你好 " + param1 + " " + param2);
    });

    $('#foo').trigger('custom', ['Custom', 'Event']);


    $("p").on("myCustomEvent", function(event, myName) {
        $(this).text(myName + ", hi there!");
        $("span")
            .stop()
            .css("opacity", 1)
            .text("myName = " + myName)
            .fadeIn(30)
            .fadeOut(1000);
    });
    $("button").click(function() {
        $("p").trigger("myCustomEvent", ["John"]);
    });

    //移除事件
    function aClick() {
        $("#test-unbind").show().fadeOut("slow");
    }
    $("#bind").click(function() {
        $("body").on("click", "#theone", aClick).find("#theone").text("Can Click!");
    });
    $("#unbind").click(function() {
        $("body").off("click", "#theone", aClick)
            .find("#theone").text("Does nothing...");
    });


});
</script>

</head>

<body>
<div id="testBox"></div>
<div id="test"></div>
<button id="btn">点击我</button>
<div id="foo"></div>
<button id="theone">Does nothing...</button>
<button id="bind">Add Click</button>
<button id="unbind">Remove Click</button>
<div id="test-unbind" style="display:none;">Click!</div>
</body>

</html>
</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容