导入 jQuery 后的 JavaScript 函数 "not defined"

标签 javascript jquery

我有以下(简化的)代码:

<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Test</title>

        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js" />

        <script language="javascript" type="text/javascript">
            function testFunction() {
                alert('It works');
            }
        </script>
    </head>
    <body>
        <form method="post" action="test.html" onsubmit="testFunction()">
            <input type="submit" value="Test" />
        </form>
    </body>
</html>

我的 testFunction() 函数本身工作得很好,直到我使用以下行导入 jQuery

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js" />

现在它失败了并告诉我 Uncaught ReferenceError :testFunction未定义

我希望这是一个新手错误,并且我错过了一些明显的东西。请注意,我什至还没有尝试使用 jQuery。

最佳答案

您需要关闭 <script>完全标记。

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

更改后在 jsfiddle 上工作得很好: http://jsfiddle.net/PVYM9/

此外,在 HTML5 中,您可以将文档类型缩短为 <!DOCTYPE html> ,并且您不需要定义 type为您提供的属性<script>标签。例如,请参见 jsfiddle。

关于导入 jQuery 后的 JavaScript 函数 "not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13933205/

相关文章:

javascript - Angular 在尝试下载文件时将 "unsafe"添加到 url

php - 使用 javascript 时将函数值传递给输入 id

javascript - onclick 复选框将复选框值附加到 URL

jquery - fancybox 内容未隐藏

javascript - 位置属性不会在 ipad 或 iphone 上重新定位

javascript - 当鼠标/光标点击弹出窗口时如何使用非事件和事件背景弹出

javascript - 最高 promise .catch 不会在返回的子 promise 拒绝时触发

javascript - 我该如何在React容器组件中进行API调用?

javascript - 重新初始化数据表

javascript - jQuery 动画不适用于左属性