Why jQuery event not firing when outside ready function, even after document is ready?

浪尽此生 提交于 2019-12-11 02:32:42

问题


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.");
});

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.


回答1:


$(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.

You just need to make sure you put the binding logic within the ready handler.




回答2:


If you want that code to be executed in the "ready" event, just move it there.

$(document).ready(function() {
    console.log("ready!");

    $("p").click(function() {
        alert("You clicked on paragraph.");
    });
});

The way you defined it right now doesn't mean it is executed when the DOM is loaded.




回答3:


You can place the code directly in the $(document).ready() function or create a new function that binds the click when the DOM is ready.

    $(document).ready(function() {
        bindClickEvent();
    });

    function bindClickEvent() {
       $("p").click(function() {
           alert("You clicked on paragraph.");
       });
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<p>Click me!</p>


来源:https://stackoverflow.com/questions/41665382/why-jquery-event-not-firing-when-outside-ready-function-even-after-document-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!