功能没有定义虽然它看起来像我定义

时间:2014-01-02 06:31:54

标签: javascript jquery

这是我的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?&nbsp;&nbsp;&nbsp;#00ff00</h2><ul>");
document.write("<li><input type='radio' name='color1' id='red' />&nbsp;&nbsp;red</li>");
document.write("<li><input type='radio' name='color1' id='green' />&nbsp;&nbsp;green</li>");
document.write("<li><input type='radio' name='color1' id='blue' />&nbsp;&nbsp;blue</li>");
document.write("<li><input type='radio' name='color1' id='teal' />&nbsp;&nbsp;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()

1 个答案:

答案 0 :(得分:3)

每个函数都会创建一个新范围,即使是这个范围(在文档级别)

$(document).ready(function(){...

所以fsubmit函数超出范围,删除包装$(document).ready函数,或者专门使用窗口命名空间

window.fsubmit = function() {
    // your function here
}

或更好的想法,使用适当的事件处理程序