如何从我的 HTML/JavaScript 应用程序中引用 jQuery?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20398021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I reference jQuery from my HTML/JavaScript application?
提问by Carlos Miguel Fernando
I keep getting Uncaught ReferenceError: $ is not defined
error.
I assume everything is ok and working. My JQuery code is inside my Javascript file. I assume that isn't how it works? Should I have a JQuery file?
我不断收到Uncaught ReferenceError: $ is not defined
错误。我假设一切正常并且工作正常。我的 JQuery 代码在我的 Javascript 文件中。我认为这不是它的工作原理?我应该有一个 JQuery 文件吗?
I have this inside the head of my HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
我在我的 HTML 的头部里面有这个
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
This is my Javascript file:
这是我的 Javascript 文件:
function typing(id, sentence){
var result = $.Deferred();
var index=0;
var intObject= setInterval(function() {
document.getElementById(id).innerHTML+=sentence[index];
index++;
if(index==sentence.length){
clearInterval(intObject);
}
}, 100);
return result.promise();
}
var sleep = function(ms) {
var result = $.Deferred();
setTimeout(result.resolve, ms);
return result.promise();
};
typing('container','Subject Name:').then(function() {
return sleep(500);
}).then(function() {
return typing('container',' Carlos Miguel Fernando')
});
Where did I go wrong?
我哪里做错了?
回答by T.J. Crowder
Your question is fairly unclear, but essentially, you just have to make sure jQuery is loaded beforeyour code. So for instance:
您的问题相当不清楚,但本质上,您只需要确保在您的代码之前加载了 jQuery 。所以例如:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="your-code.js"></script>
or
或者
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
// Your code
</script>
But not
但不是
<!-- Not like this -->
<script src="your-code.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
Note the order of tags.
注意标签的顺序。
These tags do not need to be in the head
, and in fact, putting them there is not best practice. They must be in head
or body
. Best practice barring a specific reason to do something else is to put them at the very end of body
, e.g.:
这些标签不需要在 中head
,事实上,把它们放在那里并不是最佳实践。它们必须在head
或 中body
。除非有特定原因做其他事情的最佳实践是将它们放在 的最后body
,例如:
<!-- site content here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="your-code.js"></script>
</body>
</html>