Javascript jquery中的简单自定义事件

Javascript jquery中的简单自定义事件,javascript,jquery,Javascript,Jquery,我正在尝试学习jquery自定义事件 我需要在页面加载时触发一个简单事件 HTML: 我尝试了下面的代码 function customfun() { $("#mydiv").trigger("custom"); } $(document).ready(function () { $("#mydiv").bind(customfun, function () { alert('Banana!!!');

我正在尝试学习jquery自定义事件

我需要在页面加载时触发一个简单事件

HTML:

我尝试了下面的代码

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

    $(document).ready(function () {

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

    });

您需要绑定到与您触发的事件名称相同的事件名称——“custom”。像这样:

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

您可以这样称呼它:

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

$("div").mycustom();

要将自定义事件作为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();
    });
});

bind()希望参数1是字符串或对象,而不是函数。
.on()
是下一个
.bind()
。::)谢谢你的回答。我在一些代码示例中看到,人们使用$(“#mydiv”).customevent();除了内置的clickevnts…等。那我怎么能称之为这样的事件呢?
$.fn.mycustom = function(){
     return this;
};

$("div").mycustom();
$(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();
    });
});