下面的代碼,用我自己寫(xiě)的方法getByclass同樣可以取到包含16個(gè)元素的數(shù)組,但是不能得到屬性值width,顯示錯(cuò)誤Cannot read property 'width' of undefined,如果把自己寫(xiě)的方法換成getElementsNameByTagName("div"),就可以取到寬度值50px,不懂為什么。麻煩大神幫看看,謝謝了~~???<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html" charset="utf-8"><title></title><style>div,p,ul,li{margin:0;padding:0;}li{list-style: none;}a{text-decoration:none;}div{position: relative;}body{}.redCube{width:50px;height: 50px;background: red;position: absolute;}#s{width: 100px;height: 100px;background: blue;}</style><script>window.onload=function(){var b = document.getElementById("s");var str = "";for(var i=0;i<16;i++){str += "<div class='cube' style='width:50px;height: 50px;background: red;position: absolute;left:"+i*70+"px;' ></div>";?}document.body.innerHTML=str;var timer = null;var num = 0;var oCubes = getByClass(document,"cube");alert(oCubes[0].style.width); ?};?function getStyle(obj,attr){return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj,null)[attr];};function getByClass(obj,Name){var arr = [];obj= obj?obj:document;?var aElement = obj.getElementsByTagName('*');for(var i=0;i<aElement.length;i++){if(aElement[i].className==Name){arr.push(obj);}?}?return arr;};</script></head><body></body></html>
幫忙看一下非常感謝,實(shí)在不懂為什么用class名取出來(lái)的元素,沒(méi)辦法取到屬性值?
EverDream3726731
2018-02-27 11:48:33