这个javascript代码getElementById有什么问题?

时间:2012-09-06 14:04:49

标签: javascript html getelementbyid

我在下面有这个代码..

<script>  document.getElementById('example').style.background-color =
'#FFCC00';    
</script>
<div id="example">This is an example.</div>

为什么不起作用?

5 个答案:

答案 0 :(得分:7)

脚本在具有给定id的元素存在之前运行,并且您有一个带有连字符的DOM property name(被视为减号运算符)。

<!-- Put the element first -->
<div id="example">This is an example.</div>
<script>
    // camelCase CSS property names when converting to DOM property names
    document.getElementById('example').style.backgroundColor = '#FFCC00';    
</script>

查看上述snippit的live example

您可以将JS语句包装在函数中,然后在元素存在后调用它,而不是将元素放在第一位。您可以通过将event handler绑定到合适的位置(例如文档load event)来自动执行此操作。

答案 1 :(得分:2)

你应该写backgroundColor

答案 2 :(得分:1)

需要在代码中更改的2件事。

  1. 原样,您的代码顺序错误。您需要首先使用HTML,然后使用JS。该元素尚未按此顺序存在,JS首先被执行而DOM对象尚未存在。

  2. 没有“背景颜色”属性。而是使用“.backgroundColor”。破折号通常用骆驼套管代替。

  3. 以下是一个工作示例

    <div id="example">This is an example.</div>
    
    <script>
      document.getElementById('example').style.backgroundColor = '#FFCC00';
    </script>
    

    另一个提示

    如果要将订单作为依赖项删除,可以将JavaScript包装在“onload”事件处理程序中。

答案 3 :(得分:0)

<script>更改为您的元素下方并使用backgroundColor

<div id="example">This is an example.</div>
<script>  
    document.getElementById('example').style.backgroundColor ='#FFCC00';    
</script>

答案 4 :(得分:0)

更新:

<div id="example">This is an example.</div>
<script>document.getElementById('example').style.setProperty('background-color','#fco','important');</script>

,不需要“重要”