Execute external jQuery code without calling an explicit function
I wrote some jQuery code in an external file, with the goal to match each <select>
tag in the page where the script is included.
My goal would be to include the script reference in the <head>
tag of the target pages and "run" the jQuery code without having to call any function.
I have seen several examples with external jQuery code, but all call a function to execute the (external) code.
If I use "plain" javascript, like simple alerts, they are executed without problem. When I try with my jQuery code, nothing happens.
Here is my external jQuery file:
$(function() {
$("select").focus(function() {
alert('selected...');
}).change(function() {
alert('changed...');
})
});
Even if I do not use $(function(
) at the beginning I always get the exception "Object Expected" at the first occurrence of $
, while even leaving $(function()
and inside the brackets a simple alert it works.
How the external file should be developed?
I tested the external script inline in a test page and开发者_StackOverflow中文版 it works fine.
It makes no difference where your code is written, either inline in your HTML page, or included via <script src='...'>
.
The issue then would be that jQuery has not yet been included by the time your code is being executed. Take a look at the order which you're including your files, and ensure that jQuery comes before this code which relies upon it.
You may be executing the jQuery code before jQuery has been loaded. In that case calls to docready ($(function(){})) would fail because $ !== jQuery yet. Usually to accomplish something like this I would put some code towards the bottom of my file akin to:
$(function(){
var t = "external_file.js",
s = document.createElement("script"),
h = document.getElementsByTagName("head");
s.src = t;
s.type = "text/javascript"
h.appendChild( s );
})
Try this:
$(document).ready(function() {
$("select").focus(function() {
alert('selected...');
}).change(function() {
alert('changed...');
})
});
精彩评论