[英]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!!!');
});
});
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.