In most tutorials, there are two ways mentioned about how to execute a jquery script:
- with
window.onload
hook. - with a
$(document).ready(function(){...})
event (and could be abbreviated to$(function(){...})
)
And I found that it even works when I omit all them, just place the code in a <script></script>
occlusion could achieve the same purpose. Just like this:
<html>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<body>
<button id="btn" name="test" value="clickme">clickme</button>
</body>
<script>
//$(document).ready( function(){
// $('#btn').on("click", function(e){
// alert("hi")
// }
//)})
$('#btn').on('click', function(e){
alert('hi')
})
</script>
</html>
As you can see both the un-commented code (which omit all the document.ready
staff or a window.onload
) and the commented code can give me a alert as expected.
So my question is, in such cases(binding events), since I can write code more elegant as the un-commented snippet. Why should I bother to write the code as in most tutorials told (which is as the commented style above) ?