您好我是Javascript的新手,我试图在窗口加载后尝试删除一些元素。
这是HTML
<html>
<head>
<title>Simple Quiz</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Quiz</h1>
<h2>Question</h2>
<p id="question"></p>
<form name="choices">
<fieldset>
<!-- insert questions here dynamically via javascript! -->
<label><input type="radio" name="choice" value="1st">First-class</label>
<label><input type="radio" name="choice" value="2day">2-day Air</label>
<label><input type="radio" name="choice" value="overnite">Overnight</label>
</fieldset>
</form>
</body>
</html>
函数removeQuestions()在页面加载后在控制台中调用时工作正常,但我似乎无法使用窗口的onload事件使其工作。有趣的是,它适用于JSFiddle(找到here)但不是当我在chrome中本地启动页面时。我不对的是什么?谢谢
这是script.js文件:
// JS executed after window has been loaded
function removeQuestions() {
var choices = document.forms.choices.elements[0].children;
// remove choices
while (choices.length > 0) {
var choice = choices[0];
choice.parentNode.removeChild(choice);
}
}
window.onload = removeQuestions();
答案 0 :(得分:18)
您没有将功能分配给window.onload
,而是调用您的功能,然后将结果分配给window.onload
将window.onload = removeQuestions();
替换为window.onload = removeQuestions;
浏览器期望回调函数处于onload状态,以便在加载窗口时它可以调用它。
window.onload = removeQuestions();
相当于
var result = removeQuestions(); // undefined, the function does not return anything
window.onload = result;