window.onload不适用于非常简单的页面

Eug*_*Kim 5 javascript

嗨,我是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>
Run Code Online (Sandbox Code Playgroud)

函数removeQuestions()在页面加载后在控制台中调用时工作正常,但我似乎无法使用窗口的onload事件使其工作.有趣的是,它适用于JSFiddle(在这里找到),但不是当我在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();
Run Code Online (Sandbox Code Playgroud)

Lep*_*eus 20

您没有分配您的功能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;
Run Code Online (Sandbox Code Playgroud)

  • 嗯,我仍然没有从页面得到任何响应=/ (2认同)

szi*_*qui 6

就我而言,它不起作用,因为我设置了window.onload同一页面上运行的两个脚本。我花了一些时间才意识到这个错误,因为第一个脚本有 console.log 消息,但第二个脚本没有任何消息。浏览器在第一个脚本之后加载了第二个脚本,我的 window.onload = somefunction 现在被设置为一个没有任何 console.log 的函数,给我的印象是它根本不起作用


Ben*_*ang 5

为了简单起见,回调应该是这样的:

window.onload = (event) => {
  console.info('Page is fully loaded');
  removeQuestions();
};
Run Code Online (Sandbox Code Playgroud)