jQuery不能在外部JavaScript中工作 [英] jQuery not working in external JavaScript
问题描述
我是jQuery的新手,并且遇到了一些奇怪的问题。我正在使用jQuery的更改
和点击
方法。它们在< script>
标记中的HTML文件中使用时工作正常。
p>
< script>
$(select,input)。change(function()
{
// My code and some alerts
});
< / script>
当我在外部JavaScript代码中复制相同的代码而没有< script>
并导入到我的HTML中,它根本不起作用。
在外部JavaScript代码中是否需要使用jQuery进行更改?
PS:一些其他非jQuery函数存在于相同的外部JavaScript代码中,可以从HTML中成功调用。
jQuery的技巧是你的代码被设置为立即执行。
你想包装你的脚本,以便在文档准备就绪时加载它例如:
$(document).ready(function(){
$(select,input) .change(function()
{
// My code and some alerts
})
});
和要确保你的文件在jQuery否则$ global将不会被设置)。
增加:
以下是HTML的外观:
< script type =text / javascriptsrc =https ://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js>< /脚本>
< script type =text / javascriptsrc =jscript / myExternalJs.js>< / script>
以下是您的JavaScript代码的外观(请注意JavaScript文件中没有script标签) :
$(document).ready(function(){
$(select,input)。change (函数()
{
//我的代码和一些提示
})
//其他事件处理函数
});
就您的其他脚本而言......这取决于您在做什么。最重要的是不要尝试将事件监听器绑定到尚不存在的对象上,这就是为什么我们使用 document.ready
。
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 called 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
.
这篇关于jQuery不能在外部JavaScript中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!