如何使用jQuery触发自定义事件? [英] How to trigger custom event with jQuery?
本文介绍了如何使用jQuery触发自定义事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将自定义事件处理程序附加到jQuery的 ready
方法中的 body
。
之后,我立即<触发了自定义事件 ,但似乎没有任何反应。
I'm attaching a custom event handler to the body
in jQuery's ready
method.
Afterwards I immediately trigger
the custom event but nothing seems to happen.
$(function(){
$("body").on("test", function(){ alert("test triggered"); }
$("body").trigger("test");
}
推荐答案
首先,您有语法错误
$(function(){
$("body").on("test", function(){
alert("test triggered");
}); < ---- Missing this
$("body").trigger("test");
});
第二,您无法触发控制台中的事件,如 $(function(){});
形成闭包,您将无权访问其中的任何方法他们
Secondly you cannot trigger the event from the console , as $(function() {});
forms a closure and you will not have access to any of the methods inside them
要使其正常工作,请在脚本文件中放置一个调试点,然后尝试触发事件。由于事件在范围内,因此现在可以使用。
For it to work like you are expecting , put a debug point in your script file and then try to trigger the event. It works now as the events are in scope.
这篇关于如何使用jQuery触发自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文