展开收缩,用事件代理来写的话怎样写,总是有问题,求助

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#ul1 {width: 100px; padding: 0;}
#ul1 li {width: 100px; list-style: none;}
#ul1 li h2 {margin: 0; padding: 0; height: 20px; background: #ccc; font-size: 12px; font-weight: normal; text-align: center; line-height: 20px; border: 1px solid #333;}
#ul1 li div {height: 100px; background: red; display: none;}

</style>

</head>

<body>
  <ul id="ul1">
          <li>
            <h2> 1111 </h2>
            <div id="a1"></div>
    </li>
          <li>
            <h2> 2222 </h2>
            <div id="a2"></div>
    </li>
          <li>
            <h2> 3333 </h2>
            <div id="a3"></div>
    </li>
          <li>
            <h2> 4444 </h2>
            <div id="a4"></div>
    </li>
  </ul>

  <script>
window.onload=function(){
        var ul=document.getElementById('ul1');
        var li=ul.getElementsByTagName('h2');
        var div=ul.getElementsByTagName('div');

        ul.addEventListener('click', function(e){
                
                if(e.target.parentNode.tagName = 'LI'){

                        for(var i=0; i<div.length; i++){
                                div[i].style.display = 'none'
                        }
                        console.log(e.target.parentNode,e.target.parentNode.getElementsByTagName('div')[0])
                        var elem = e.target.parentNode.getElementsByTagName('div')[0];
                        if(elem.show==1){
                                elem.style.display = 'none'
                                elem.show=0
                        }else{
                                elem.style.display = 'block'
                                elem.show=1;
                        }
                }
        })
};
</script>
</body>
</html>


jingjing83
浏览 1104回答 2
2回答

qq_青枣工作室_0

用jquery就好啦,做人不要太累
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript