5

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

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

HTML:

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

我需要调用自己的事件来触发警报

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

我尝试了下面的代码。

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

    $(document).ready(function () {

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

    });
4

3 回答 3

4

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

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

小提琴

于 2013-08-01T07:37:40.043 回答
2

要将自定义事件调用为您需要的 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();
    });
});
于 2013-08-01T08:15:48.260 回答
0

你可以这样调用它:

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

$("div").mycustom();
于 2013-08-01T07:52:01.940 回答