简体   繁体   English

如何在jQuery中定义自己的事件?

[英]How can i define my own event in jQuery?

如何在jQuery中定义自己的事件?

Define and attach your own custom events with .bind() : 使用.bind()定义并附加您自己的自定义事件:

// make myObject listen for myFancyEvent
$('#myobject').bind('myFancyEvent', function(){
  alert('Yow!');
});

...then .trigger() them directly: ...然后直接.trigger()它们:

$('#myobject').trigger('myFancyEvent');

...or mixed in with other event handlers: ...或与其他事件处理程序混合使用:

$('#myobject').click( function(){
  doSomething();
  $(this).trigger('myFancyEvent');
});

You shouldn't have trouble finding a lot of information on the subject. 您可以轻松找到有关该主题的很多信息。 This article is a couple of years old, but still a good overview. 本文已有两年历史,但仍然是一个不错的概述。

Refer to this link . 请参阅此链接

Here are some code snippet from the article above. 这是上面文章的一些代码片段。

You can trigger custom events on any DOM object of your choosing using jQuery. 您可以使用jQuery在您选择的任何DOM对象上触发自定义事件。 Just trigger it using the following code: 只需使用以下代码触发它:

$("#myelement").trigger('fuelified');

You can subscribe to that event using either bind or live functions in jQuery: 您可以使用jQuery中的绑定或实时功能订阅该事件:

$("#myelement").bind('fuelified',function(e){ ... });
$(".cool_elements").live('fuelified',function(e){ ... });

You can even pass additional data about the event when triggering it and reference it on the listeners end: 您甚至可以在触发事件时传递有关事件的其他数据,并在侦听器端对其进行引用:

$("#myelement").trigger('fuelified',{ custom: false });
$("#myelement").bind('fuelified',function(e,data){ if(data.custom) ... });

The element the trigger has been called on, is available to listener's callback function as the variable this. 调用触发器的元素,作为变量this,可用于侦听器的回调函数。

You can throw events like this: 您可以抛出以下事件:

$("#element").trigger("your.event", [ 'Pamela', 'Anderson' ] );

Note that extra parameters should be passed as an array. 请注意,应将额外参数作为数组传递。

How to listen for events: 如何监听事件:

$("#element").bind("your.event", function(event, firstName, lastName) { 
    // Callback
});

The "#element" selector can be substituted with document if the event isn't specific for a particular dom node. 如果事件并非特定于特定的dom节点,则可以用文档替换“ #element”选择器。

jQuery documentation: Bind Trigger jQuery文档: 绑定 触发器

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

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