结果是正确的,但控制台显示Uncaught TypeError:无法设置null的属性'innerHTML'

时间:2016-01-03 18:52:33

标签: javascript html

我正在获得所需的输出,但控制台正在显示

  

Javascript:Uncaught TypeError:无法设置属性'innerHTML'   空

我尝试了其他SO answers,但他们给了我不同的问题。

这是我的代码:

var dogs = ["Jimmy","Rudolph","Rocky","Sweezy"];

for (var i = 0; i <= dogs.length; i++) {
	document.getElementById('dogName' + (i+1) ).innerHTML = dogs[i];
	console.log(dogs[i]);
}
<div>
    <h3>My name is <span id="dogName1"></span></h3>
    <img src="https://placeimg.com/140/180/animals">
</div>
<div>
    <h3>My name is <span id="dogName2"></span></h3>
    <img src="https://placeimg.com/140/180/animals">
</div>
<div>
    <h3>My name is <span id="dogName3"></span></h3>
    <img src="https://placeimg.com/140/80/animals">
</div>
<div>
    <h3>My name is <span id="dogName4"></span></h3>
    <img src="https://placeimg.com/140/180/animals">
</div>

1 个答案:

答案 0 :(得分:1)

尝试将&lt; =更改为&lt;。你的循环运行时间过多,最后一个元素dogName5不存在

var dogs = ["Jimmy","Rudolph","Rocky","Sweezy"];

for (var i = 0; i < dogs.length; i++) {
    document.getElementById('dogName' + (i+1) ).innerHTML = dogs[i];
    console.log(dogs[i]);
 }

HTML:

<div>
<h3>My name is <span id="dogName1"></span></h3>
<img src="https://placeimg.com/140/180/animals">
</div>
<div>
<h3>My name is <span id="dogName2"></span></h3>
<img src="https://placeimg.com/140/180/animals">
</div>
<div>
    <h3>My name is <span id="dogName3"></span></h3>
    <img src="https://placeimg.com/140/80/animals">
</div>
<div>
   <h3>My name is <span id="dogName4"></span></h3>
   <img src="https://placeimg.com/140/180/animals">
</div>