使用 node.js 时不能影响带有 javascript 的 div?

Can't affect divs with javascript when using node.js?

我可能做了一些明显错误的事情,但我正在使用 node.js 并且我有一个正确链接的 javascript 文件(alert("hello"); 有效)。但是我不能用 DOM 影响任何东西。简单示例:

翡翠:

doctype html
html
    head
        link(rel='stylesheet', href='/stylesheets/styles.css')
        script(src='/javascripts/script.js')
    body
        block index_block
        div#divClassName

手写笔:

#divClassName
    background-color red
    width 200px
    height 200px

js:

alert("hello");

var div = document.getElementById("divClassName");

div.style.backgroundColor = "green";

框保持红色。为什么?谢谢。

由于您的脚本 运行 在 HTML 被读取之前,div 变量 returns 未定义,因为在您的脚本执行时不存在这样的元素.将您的 JS 包装在文档的函数 onload 中允许您推迟执行,直到文档完全加载。

window.onload = function(){
    alert("hello"); 
    var div = document.getElementById("divClassName");
    div.style.backgroundColor = "green";
}