我创建了一个带有几个按钮的小网站。每个按钮都应该调用先前定义的 JS 函数。但是,每次按下按钮时,我都会收到一个 ReferenceError ,指出该函数未定义。
(index):1 Uncaught ReferenceError: mainLightOn is not defined
这是我网站的代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Home Cinema Control Center</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
<style type="text/css">
td {
padding: 10px;
}
body {
font-family: Segoe UI, Arial, sans-serif;
background-color: #636363;
}
p {
color: #3b3b3b;
font-size: 4.0em;
}
.btn-xlarge {
padding: 18px 28px;
font-size: 3.5em;
line-height: normal;
border-radius: 8px;
}
.box {
background-color: #fbfbfb;
margin: 120px auto;
padding: 20px;
border-radius: 5px;
box-shadow: 10px 15px 20px rgba(0, 0, 0, 0.3);
}
</style>
<script type="text/javascript">
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// Add stuff later
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
function mainLightOn() {
httpGetAsync("/api/mainlight/1");
}
function mainLightOff() {
httpGetAsync("/api/mainlight/0");
}
</script>
</head>
<body>
<div class="box" style="width:90%; display:table">
<table style="width:100%">
<tr>
<td style="width:40%;">
<p>Main Light</p>
</td>
<td style="width:30%;">
<button type="button" class="btn btn-success btn-xlarge btn-block" onclick="mainLightOn()">On</button>
</td>
<td style="width:30%;">
<button type="button" class="btn btn-danger btn-xlarge btn-block" onclick="mainLightOff()">Off</button>
</td>
</tr>
</table>
</div>
</body>
</html>
奇怪的是,只有当我从服务器打开网站时才会发生该错误。当我在笔记本电脑上本地打开 html 时,函数调用正常。
最佳答案
您的函数定义位于 $().ready(function() {... })
主体内,因此作用域就是该函数。从 HTML 元素执行的 JavaScript 是在全局范围内执行的。
无需将这些函数放入$().ready()
中。仅当代码必须等到 DOM 准备好才能运行时,才需要将代码放在那里。但这些函数只有在用户点击元素时才会执行,而在 DOM 准备好之前不会发生。
关于javascript - Uncaught ReferenceError - 函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39668892/