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

what's wrong with this javascript code getElementById?

本文关键字:代码 getElementById 有问题 javascript 这个 什么      更新时间:2023-09-26

我有下面的代码。。

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

为什么它不起作用?

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

<!-- 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>

请参阅以上狙击坑的一个实际示例。

您可以将JS语句封装在一个函数中,然后在元素存在后调用它,而不是将元素放在第一位。您可以通过将它作为事件处理程序绑定到合适的东西(例如文档加载事件)来自动实现这一点。

您应该编写backgroundColor

代码中需要更改的两件事。

  1. 实际上,您的代码顺序错误。您需要先拥有HTML,然后才拥有JS。元素还没有按这个顺序存在,JS首先被执行,DOM对象还没有出现。

  2. 没有"背景色"属性。请使用".backgroundColor"。破折号通常用驼色大小写代替。

下面是一个工作示例

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

另一个提示

如果您想将订单作为依赖项删除,可以将JavaScript封装在"onload"事件处理程序中。

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

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

更新:

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

,不需要"重要"