简体   繁体   English

将Javascript对象转换为dom元素

[英]convert Javascript object to dom element

I've had this confusion since long. 我很久以来就有这种困惑。 There is an error called cannot read property of null on chrome inspector. 在chrome检查器上有一个名为无法读取null属性的错误。

Upon searching and reading, i found that a property (eg style) can be applied to a DOM element, but if it is rendered as a javascript object it gives the above error. 在搜索和阅读时,我发现可以将属性(例如样式)应用于DOM元素,但如果将其呈现为javascript对象,则会产生上述错误。

So how do i go about this? 那我该怎么做呢?

<html>
    <head>
        <style>
            #test {background:black;width:30px;height:30px;}
        </style>
        <script>
            var a = document.getElementById('test');
            a.style.background = "#f00";
        </script>
    </head>
    <body>
            <div id="test">
            </div>
</body>
</html>

When i did alert(typeof a); 当我做警报时(a型); it gives as object. 它给出了对象。 So how do I, in general, change properties of elements ?? 那么,一般来说,我如何改变元素的属性?

The issue is that #test doesn't exist when the script is executed. 问题是脚本执行时#test不存在。 The script is executed immediately as the page is loaded, and at the point when the browser executes the script, it hasn't gotten to <div id="text"></div> , so document.getElementById('test') returns null . 在加载页面时立即执行脚本,并且在浏览器执行脚本时,它没有得到<div id="text"></div> ,因此document.getElementById('test')返回null

null values don't have properties, so calling: a.style.background... causes JavaScript to error out. null值没有属性,因此调用: a.style.background...会导致JavaScript出错。 If you'd attached this script to body.onload , the callback function provided would execute after the rest of the page was loaded: 如果您将此脚本附加到body.onload ,则提供的回调函数将加载页面的其余部分执行:

document.body.onload = function(){
  var a = document.getElementById('test');
  if ( a ) //just a check to make sure that `a` was set so that it doesn't error again.
  {
    a.style.background = "#f00";
  }
};

Your javascript is running before the page has finished loading. 您的javascript在页面加载完成之前正在运行。

You need to put your javascript inside an window.onload like this: 你需要将你的javascript放在window.onload中,如下所示:

window.onload = function()
{
  var a = document.getElementById('test');
  a.style.background = "#f00";
}

You need to wait for the DOM to be completely loaded before calling that script, because when you are calling the code the element isn't created yet. 在调用该脚本之前,您需要等待DOM完全加载,因为在调用代码时,元素尚未创建。

http://jsfiddle.net/m5Qqs/1/ http://jsfiddle.net/m5Qqs/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM