this is a simple html file:
<!DOCTYPE html>
<html>
<head>
<title>Test Uploading Func.</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery-1.7.2.js"> </script>
<link type="text/css" href="jquery-ui-1.8.21.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="jquery-ui-1.8.21.custom.min.js"></script>
<!--Include js file-->
<script type="text/javascript" src="upload.js" ></script>
</head>
<body>
<button id="Upload" value="upload">upload</button>
<script type="text/javascript" src="upload.js" ></script>
</body>
And this is the js file I want to include:
$( '#Upload' ).bind('click', function(){
alert(">");
});
If I just include the js file in the beginning, the selector # can’t know the id Upload so that I have to include it again
at the end of the file… I do know it’s not correct. But I don’t know how to resolve it? Don’t we just include all the js file within the tag head?
What’s the appropriate coding style I show have?
Thanks.
UPDATE question!!!
If I have a lot of scenario like this, should I add “$(document).ready()” to all the functions? A little weird…
Still another approach? Or web developers always do so.
And where should I include my js file? In the begin or the end?
If I include them all in the end, this kind of problem won’t appear.
Then why lots of people include the js file just in the start?
Wait for the DOM to be ready before selecting elements:
Update:
You should always use
$(document).ready(...)if you are manipulating elements that you expect to be on the page when your code runs. This is especially important if your code is in the<head></head>of the document.You are not required to use
$(document).ready(...)if your code is inside the</body>tag, but be aware that there are differences between the two.