最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why jQuery event not firing when outside ready function, even after document is ready? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Jan 15, 2017 at 19:34 Darren 70.9k24 gold badges141 silver badges145 bronze badges asked Jan 15, 2017 at 19:29 Marcin LentnerMarcin Lentner 851 silver badge6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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

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.

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./ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<p>Click me!</p>

发布评论

评论列表(0)

  1. 暂无评论