这是我的HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>write html with jquery</title>
<style>
li {list-style:none;}
.green {color:#00FF00;}
.red {color:#FF0000;}
#result {font-size:3em; margin: 2em 0 0 3em;}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/write_form.js"></script>
</head>
<body>
<div id="result"> </div>
</body>
</html>
这是我的Javascript:
$(document).ready(function(){
function fsubmit() {
var answer = document.getElementById("green");
var result = document.getElementById("result");
if(answer.checked == true) {
result.className = "green"; result.innerHTML="correct!";
} else {
result.className = "red"; result.innerHTML="wrong";
}
}
document.write("<header><h1>Html quiz</h1></header>");
document.write("<article><h2>What color is this? #00ff00</h2><ul>");
document.write("<li><input type='radio' name='color1' id='red' /> red</li>");
document.write("<li><input type='radio' name='color1' id='green' /> green</li>");
document.write("<li><input type='radio' name='color1' id='blue' /> blue</li>");
document.write("<li><input type='radio' name='color1' id='teal' /> teal</li>");
document.write("<li><input type='submit' name='submit' value='Submit' onClick='fsubmit()' /></li></ul></article>");
});
这是我收到的错误消息:
Uncaught ReferenceError: fsubmit is not defined write_test.html:1
在文档准备就绪后,我首先要做的是定义函数fsubmit()
。
答案 0 :(得分:3)
每个函数都会创建一个新范围,即使是这个范围(在文档级别)
$(document).ready(function(){...
所以fsubmit
函数超出范围,删除包装$(document).ready
函数,或者专门使用窗口命名空间
window.fsubmit = function() {
// your function here
}
或更好的想法,使用适当的事件处理程序