执行外部 jQuery 代码而不调用显式函数
我在外部文件中编写了一些 jQuery 代码,目的是匹配包含脚本的页面中的每个
我的目标是将脚本引用包含在目标页面的 标记中,并“运行”jQuery 代码,而无需调用任何函数。
我见过几个使用外部 jQuery 代码的示例,但它们都调用函数来执行(外部)代码。
如果我使用“普通”javascript,比如简单的警报,它们的执行不会有问题。当我尝试使用 jQuery 代码时,没有任何反应。
这是我的外部 jQuery 文件:
$(function() {
$("select").focus(function() {
alert('selected...');
}).change(function() {
alert('changed...');
})
});
即使我在开始时不使用 $(function(
)),我总是会在第一次出现 $
时收到异常“Object Expected” ,即使留下 $(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 it works fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无论您的代码是内嵌在 HTML 页面中,还是通过
包含,在何处都没有区别。
那么问题是在执行代码时 jQuery 尚未包含在内。查看包含文件的顺序,并确保 jQuery 位于依赖它的代码之前。
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.
您可能在加载 jQuery 之前执行 jQuery 代码。在这种情况下,对 docready ($(function(){})) 的调用将会失败,因为 $ !== jQuery 还没有实现。通常为了完成这样的事情,我会在文件底部放置一些代码,类似于:
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:
试试这个:
Try this: