本文介绍了为什么在没有外部就绪功能的情况下,即使在文档就绪之后,jQuery事件也不会触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管似乎已加载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事件也不会触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 07:09