代码在 JSFiddle 环境中运行,但在 运行 时不运行,否则

Code functioning in JSFiddle environment but not when run otherwise

所以在处理另一个问题时,, I got a great answer from @earl3s and a link to a jsfiddle of the work and it appeared to work fine but when trying to run it in repl.it 它给了我一个错误,当我尝试在本地 运行 它时,我在第 19 行读取 "Uncaught TypeError: Cannot read property 'add' of null" 时出错。我可能提交错误或代码可能编写不正确,将不胜感激。这是原始代码:

<script>
    if (window.location.href.substring(0,9) === "http://ww") {
    var home_var = "bing.com";    
    }
    else if (window.location.href.substring(0,9) === "https://p") {
    var home_var = "https://px.multiscreensite.com/index.php?url=bing.com";
    }
    else {
    var home_var = "1";
    }
    var select= document.getElementById("mySelect");
    var option = document.createElement("option");
    option.text = "Hope Page";
    option.value = home_var;
    select.add(option);
    console.log(home_var);
</script>

<select id="mySelect" OnChange="window.location.href=this.value">
    <option>Tagged Stuff and Navigation</option>
</select>

JSFiddle, the JavaScript is automatically loaded after the document loads. In repl 中,您在实际加载 dom 之前插入了 JavaScript,因此当时 mySelect 不存在。您必须在 dom 加载后添加 JavaScript,即在 body 标记的末尾。

这是一个working example