admin管理员组文章数量:1415684
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 badges3 Answers
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>
本文标签:
版权声明:本文标题:javascript - Why jQuery event not firing when outside ready function, even after document is ready? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745239835a2649261.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论