简体   繁体   English

jquery中的简单自定义事件

[英]Simple custom event in jquery

I'm trying to learn jquery custom events. 我正在尝试学习jquery自定义事件。

I need to fire a simple event on page load. 我需要在页面加载时触发一个简单的事件。

HTML: HTML:

<div id="mydiv"> my div</div>

I need to call my own event to fire an alert 我需要打电话给我自己的事件来发出警报

$("#mydiv").custom();

i tried the below code. 我尝试了下面的代码。

function customfun()
    {
        $("#mydiv").trigger("custom");
    }

    $(document).ready(function () {

        $("#mydiv").bind(customfun, function () {
            alert('Banana!!!');
        });

    });

You need to bind to the same event name -- "custom" -- as the one you triggered. 您需要绑定到相同的事件名称 - “自定义” - 作为您触发的事件名称。 Like this: 像这样:

$("#mydiv").on("custom", function () { ...

Fiddle 小提琴

To call custom events as jquery functions you need, well, define such a function via $.fn : 要将自定义事件作为jquery函数调用,您需要通过$.fn定义这样的函数:

$(document).ready(function () {
    //define the event
    $(document).on('custom', function() { 
      alert('Custom event!');
    });

    //define the function to trigger the event (notice "the jquery way" of returning "this" to support chaining)
    $.fn.custom = function(){
        this.trigger("custom");
        return this;
    };

    //trigger the event when clicked on the div
    $("#mydiv").on("click", function() {
        $(this).custom();
    });
});

you can call it by doing so: 你可以通过这样做来调用它:

$.fn.mycustom = function(){
     return this;
};

$("div").mycustom();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM