jQuery not working in external JavaScript
I am new to jQuery and am stuck at some strange issue. I am using jQuery's change
and click
methods. They are working fine when used in my HTML file in the <script>
tag.
Like:
<script>
$("select,input").change(function ()
{
// My code and some alerts
});
</script>
When I copied the same in external JavaScript code without <script>
and imported that in my HTML it was not at all working.
Are there any changes which are needed to use jQuery in external JavaScript code?
PS: Some other non-jQuery functions present in same external JavaScript code are successfully call开发者_如何学JAVAed from HTML.
First off, you don't want a <script> tag in an external JavaScript file, if that's how I'm reading your post.
The trick with jQuery is that your code is set to execute immediately.
You want to wrap your script so that it loads when the document is ready, in something like:
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
});
And you want to make sure that your file is loaded after jQuery (otherwise the $ global will not be set).
Additions:
Here is what your HTML should look like:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jscript/myExternalJs.js"></script>
Here is what your JavaScript code should look like (note there is no script tag inside the JavaScript file):
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
// Other event handlers.
});
As far as your other script... it sort of depends on what you're doing. The most important thing is to not try to hook event listeners up to objects that don't yet exist, which is why we use document.ready
.
Did you make sure jquery is defined before your own jquery code?
You should also make sure the DOM is ready when dealing with jquery:
$(document).ready(function() {
$("select,input").change(function() {
// my code and some alerts
});
// more code here if needed, etc.
});
精彩评论