2

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

<!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 is not defined

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

4

4 回答 4

7

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

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

更改后在 jsfiddle 上效果很好:http: //jsfiddle.net/PVYM9/

此外,在 HTML5 中,您可以将 doctype 缩短为 just <!DOCTYPE html>,并且无需为标签定义type属性。<script>例如,参见 jsfiddle。

于 2012-12-18T12:40:59.050 回答
2

您必须以正确的方式关闭脚本标签

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

(注意结束</script>标签)

于 2012-12-18T12:41:29.557 回答
1
   <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> // close the script tag properly

        <script type="text/javascript"> // there is no need of writing language="javascript"
            function testFunction() {
                alert('It works');
            }
        </script>

嘿伙计,不需要写 language="javascript" 因为 type 已经指定了它!

于 2012-12-18T12:41:14.210 回答
1

尽管是有效的 XML,但如果您使用尾部斜杠(即 )关闭它们,许多 HTML 元素(例如scripttextarea)在大多数浏览器中都不能正常工作<element />。您需要为它们创建打开和关闭标签才能工作 ( <element></element>)。XHTML 似乎也是如此。

其他的,比如你的input标签,就可以正常工作。我不知道为什么有些需要结束标签而有些不需要,也不是这些元素的列表,我只是从经验中知道其中一些......

于 2012-12-18T12:47:02.770 回答