[英]Define and trigger a custom event
I have the need to call a custom event on my DatatTble's cells. 我需要在DatatTble的单元格上调用自定义事件。 So, I have the following method:
因此,我有以下方法:
(function ($) {
$.fn.longClick = function (callback) {
//event
};
})(jQuery);
To make the binding, as a test, I do the following: 为了进行绑定,作为测试,我执行以下操作:
$("h1").longClick(function () {
console.log('triggered');
});
I need to replace my click event: 我需要替换点击事件:
$('#dtStatus').on('click', 'tbody td:not(:first-child)', function (e) {
console.log('triggered');
});
With my longpress event. 随着我的longpress活动。
$('#dtStatus').on('longClick', 'tbody td:not(:first-child)', function (e) {
console.log('triggered');
});
The h1
longclick and td
click event work, but the td longpress
doesn't. h1
longclick和td
click事件有效,但td longpress
无效。 Can some one tell me why I can't use my event like on('longClick')
? 有人可以告诉我为什么不能使用
on('longClick')
这样的事件吗?
Thank you. 谢谢。
I think you are mixing up functions with events. 我认为您正在将功能与事件混在一起。 With
$.fn.longClick
you created a function that you already called successfully with $("h1").longClick(...)
. 使用
$.fn.longClick
创建了一个已经通过$("h1").longClick(...)
成功调用的函数。
Now, to use it like an event, you need to trigger it first. 现在,要将其像事件一样使用,您需要先触发它。 For example:
例如:
$('#dtStatus').click(function() {
$(this).trigger("myEvent");
});
It triggers event with name myEvent
on the item that was clicked. 它在单击的项目上触发名为
myEvent
事件。 Then you can catch that event with: 然后,您可以通过以下方式捕获该事件:
$('#dtStatus').on("myEvent", function() {
alert("myEvent called!");
});
You can read more about custom events in jQuery documentation . 您可以在jQuery文档中阅读有关自定义事件的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.