我有以下(简化的)代码:
<!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/