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

Why does click event not firing in this case, although DOM appears to be loaded ('ready' show

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745239835a4618115.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信