window.onload = function () { var Ul = document.getElementsByTagName('ul')[1]; var oLi =Ul.getElementsByTagName('li'); var oLi2 =Ul.getElementsByTagName('li')[2]; addClass(oLi2,'d');//这个没问题 for(var i = 0; i <= oLi.length; i++){ addClass(oLi[i],'d'); removeClass(oLi[i],'c'); } //这一块代码有问题,不知道原因 function hasClass( elements,cName ){ return !!elements.className.match( new RegExp( "(\\s|^)" + cName + "(\\s|$)") ); }; function addClass( elements,cName ){ if( !hasClass( elements,cName ) ){ elements.className += " " + cName; }; }; function removeClass( elements,cName ){ if( hasClass( elements,cName ) ){ elements.className = elements.className.replace( new RegExp( "(\\s|^)" + cName + "(\\s|$)" )," " ); }; }; }
Determine whether an unordered list contains a certain class, and encounter problems when adding and deleting classes - PHP Chinese website Q&A - Determine whether an unordered list contains a certain class, and encounter problems when adding and deleting classes - PHP Chinese website Q&A
Have a look and learn.
这个很明显啊
循环的判断条件有问题,你一共有oLi.lenght个元素,从0开始,到oLi.length-1就够了。
这样导致oLi[oLi.length]的值为undefined,后面又读取它的属性,报错