问题描述
尽管似乎已加载DOM(控制台中显示就绪"),但为什么在这种情况下为什么不触发click事件?
Why does click event not firing in this case, although DOM appears to be loaded ('ready' shows in the console)?
$(document).ready(function() {
console.log("ready!");
});
$("p").click(function() {
alert("You clicked on paragraph.");
});
我的理解是,因为click事件的代码是在文档就绪功能正确执行后执行的,所以它应该可以工作,但不能.仅在就绪功能中的花括号之间包含事件时,此功能才有效.
My understanding, that because code for click event is after document ready function is correctly executed, it should work, but it doesn't. It will only work when event is included between curly braces in ready function.
推荐答案
$(document).ready
是异步的.您正在向其传递一个回调函数,以便它记录DOM已准备就绪的事实.但是,click
绑定代码是在设置ready
处理程序之后立即执行的,而不是在回调已执行时执行.
$(document).ready
is asynchronous. You are passing a callback function to it so that it logs the fact the DOM is ready. However, the click
binding code is being executed immediately after you set up the ready
handler, not when the callback has executed.
您只需要确保将绑定逻辑放入ready
处理程序中即可.
You just need to make sure you put the binding logic within the ready
handler.
这篇关于为什么在没有外部就绪功能的情况下,即使在文档就绪之后,jQuery事件也不会触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!