jquery在html文件中没有工作

时间:2011-02-18 07:31:30

标签: javascript jquery html

我正在尝试做一个非常基本的jquery教程但是我无法让它工作。 我正在从谷歌调用jquery库,然后我尝试在html中创建一个脚本。

如果我在.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>

2 个答案:

答案 0 :(得分:10)

您需要将其拆分:

<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>

...分为两个脚本元素:

<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>

在您提供的代码段中,<script>元素中的代码将不会被评估,因为浏览器仅评估src属性中的内容而忽略其他所有内容。

答案 1 :(得分:1)

将脚本移动到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>