javascript jquery在html文件中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5038709/
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
jquery not working inside html file
提问by Nicolas de Fontenay
I'm trying to do a very basic jquery tutorial but I'm not able to get it to work. I'm calling the jquery library from google and then I try to create a script inside html.
我正在尝试做一个非常基本的 jquery 教程,但我无法让它工作。我正在从 google 调用 jquery 库,然后我尝试在 html 中创建一个脚本。
If I do the same in a .js file I wouldn't have any problem. What am I missing here?
如果我在 .js 文件中做同样的事情,我就不会有任何问题。我在这里错过了什么?
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js">
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
</script>
<a href="">Link</a>
</body>
</html>
回答by Matt Howell
You need to split this up:
你需要把它分开:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js">
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
</script>
...into two script elements:
...分为两个脚本元素:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
</script>
In the snippet you gave, the code within the <script>element won't be evaluated because the browser is only evaluating the contents from the srcattribute and ignoring everything else.
在您提供的代码段中,<script>将不会评估元素内的代码,因为浏览器仅评估src属性中的内容而忽略其他所有内容。
回答by toddles2000
Move your scripts into the head element like this:
将您的脚本移动到 head 元素中,如下所示:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a").click(function () {
alert("Hello world!");
});
});
</script>
</head>
<body>
<a href="#">Link</a>
</body>
</html>

