jQuery在链接到外部JS时未运行

jquery not running when linked to an external js

本文关键字:运行 JS 外部 链接 jQuery      更新时间:2023-09-26

每当我将脚本放在与script.js相同的文件夹中的另一个文件中时,它都不会运行。仅当我将代码包含在脚本标记中时,它才会运行。

我用这个简单的jquery代码尝试了一下。每当第三个脚本标签未注释时,它都可以工作,但我现在的设置不会运行。

.HTML

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" scr="script.js"></script> // <!-- doesn't run -->
    <!--script> // <!-- only runs inside the html file -->
        $(document).ready(function(){
            $('p').click(function(){
                $(this).hide();
            });
        });
    </script-->
</head>
<body>
    <p>Click to hide.</p>
</body>
</html>

脚本.js

$(document).ready(function(){
    $('p').click(function(){
        $(this).hide();
    });
});

有谁知道我做错了什么?

scr不是src。使用验证器来确保您没有拼写错误的属性名称。

你的jQuery代码在脚本.js文件和.html文件中被复制,所以这就是代码无法运行的原因。

.html文件中删除 jQuery 代码,您的代码将运行。就像上面提到的一样,在您的.html文件中将 scr 替换为 src

最后,我将脚本.js文件中的代码替换为下面列出的新代码,因为 click(function(){} 是较旧的代码:

$(document).ready(function(){
    $("p").on("click", function(){
        $(this).hide();
    });
});