<!doctype?html>
<html>
<head>
????<meta?charset="UTF-8">
????<title>Document</title>
</head>
<body>
????????<ul?id="list">
????????????<li>1</li>
????????????<li>2</li>
????????????<li>3</li>
????????????<li>4</li>
????????</ul>
????????<p>class為on的p標簽</p>
</body>
</html>
<script?type="text/javascript">
??window.onload=function(e){?
????var?len1=?getByClass("on","list");
?????alert(len1.length);??//?結果等于2為正確
????var?len2=?getByClass("on");
?????alert(len2.length);??//?結果等于3為正確
}
function?getByClass(clsName,?parent){
?//定義函數getByClass()實現獲取document或指定父元素下所有class為on的元素??
????var?oP?=?parent?document.getElementById(parent):document;
????var?oOn?=?oP.getElementsByTagName("*");
????var?on?=?[];
????for?(var?i=0,len=oOn.length;i<len;i++){
????????if(oOn[i].className?==?clsName){
????????????on.push(oOn);
????????}
????}
????return?on;
}
</script>
2020-05-15
是程序后臺的原因,我把程序單獨放在文件里執行就沒有出現二次
2018-12-04
你好,應該是 onload 的原因。
2017-09-27
你這樣的len2只是把body的class為on的子元素獲取到了,所以len2.length=1;?? 我上面的len2是把所有為on的元素獲取到了,所以我的len2.length=3;?? 但是我們倆這樣提交都會彈出多下。
2017-09-27
不知道你想要的是不是這種結果。然后你獲取的是元素,不是給元素綁定事件,和事件冒泡關系不大吧,我了解的事件冒泡就是應用在動態綁定事件的時候,不知道子元素個數或者子元素個數動態變化時在父元素綁定事件,利用事件冒泡來進行事件處理。
2017-09-26
上面html里面的body 把class丟了,暈,這里補上
<body>
?? ??? ?<ul id="list">
?? ??? ??? ?<li class="on">1</li>
?? ??? ??? ?<li class="select">2</li>
?? ??? ??? ?<li class="on">3</li>
?? ??? ??? ?<li>4</li>
?? ??? ?</ul>
?? ??? ?<p class="on">class為on的p標簽</p>
</body>
2017-09-26
-----------------------------