遇到問題如下:
var children = document.querySelectorAll('.checkbutton-bg');
for(var i in children){
children[i].style.backgroundImage = 'url('+atr.norbackground+')';
}
報錯:在children[i].style中無法獲取第一層“div”的backgroundImage屬性。
解決方案:
var children = document.querySelectorAll('.checkbutton-bg');
for(var i = 0; i != children.length; i++){
children[i].style.backgroundImage = 'url('+atr.norbackground+')';
}
把for循環改成for(var i = 0; i != children.length;I++)就可以了。
原因分析:
從這個問題可以看出 for(vari=0;i!= children.length;i++) 與for(variinchildren)是有區別的。
在JS中,
測試代碼:
var children = document.querySelectorAll('.checkbutton-bg');
var k = 1;
console.log("children.length:"+children.length)
for(var i in children){
/*for(var i = 0; i != children.length; i++){*/
/*children[i].style.backgroundImage = 'url('+atr.norbackground+')';*/
console.log("K:"+ k++)
console.log(children[i])
}
顯示:
children.length:7
directive.js:84 K:1
directive.js:85 <div ng-click="toggle()" ng-transclude class="checkbutton-bg" selectbackground="img/other/jinbikuang1.png" norbackground="img/other/jinbikuang.png" style="background-image: url("img/other/jinbikuang.png"); background-size: 100% 100%; background-repeat: no-repeat;">…</div>
directive.js:84 K:2
directive.js:84 K:7
directive.js:85 <div ng-click="toggle()" ng-transclude class="checkbutton-bg" selectbackground="img/other/jinbikuang1.png" norbackground="img/other/jinbikuang.png" style="background-image: url("img/other/jinbikuang.png"); background-size: 100% 100%; background-repeat: no-repeat;">…</div>
directive.js:84 K:8
directive.js:85 7
directive.js:84 K:9
從上面可以看出,使用 for in 數組的長度應該是7,但是循環卻一直循環到8,但是沒有最後一個數組元素,進而導致報錯。
這是由於在for in 中i表示項的索引,也就是 0、1、2、3…… ,二不是項。
這還不是致命的,看下面的示例:
var arr = [1, 2];
for (var index in arr)
{
alert(index);
}
我們看到會彈出三個對話框,分別是:0、1、copy,也就是說除了項的數值索引 0、1,還多了一個 copy,而這個 copy 就是因爲 Array.prototype.copy 擴展得到的。
所以說不要把 for (var index in items) 當作是 for (var i = 0; i < items.length; i++) 的一種簡寫,二者具有不同的意義。