当点击第一个li时,它显示内容一,当点击第二个li时,它显示内容二

时间:2012-09-14 07:31:35

标签: javascript

<style type="text/css">

.web_index div {width: 400px; height: 300px; background: #eee;}
    ul li{width: 100px; height: 30px; line-height: 30px; list-style: none; display: inline-block; *display: inline; zoom: 1;}
</style>
<script type="text/javascript">
function licker(){
var lier=document.getElementsByTagName("li");
var diver=document.getElementsByClassName("web_index")[0].getElementsByTagName("div");
for(var i=0;i<lier.length;i++)
    { 
        for(j=0;j<diver.length;j++)
        {
            if(i==j)
            {
             diver[j].style.display=block;
                }
            else{
                diver[j].style.display=none;
                }   
            }
    }
}

</script>

HTML:

<ul>
    <li onclick="licker()" class="li01">the first li</li>
    <li onclick="licker()" class="li02">the second li</li>
    <li onclick="licker()" class="li03">the third li</li>
    <div class="web_clear"></div>
</ul>
<div class="web_index">
<div style="display:block" >content one</div>
<div style="display:none">content two</div>
<div style="display:none">content three</div>
</div>

点击第一个li时,显示内容一,其他都隐藏,点击第二个li时,显示内容二。其他都隐藏了....为什么我的代码不起作用。如何纠正它。谢谢你,

2 个答案:

答案 0 :(得分:1)

您应该为li指定一个索引:

<ul>
    <li onclick="licker(0)" class="li01">the first li</li>
    <li onclick="licker(1)" class="li02">the second li</li>
    <li onclick="licker(2)" class="li03">the third li</li>
    <div class="web_clear"></div>
</ul>

和你的职能:

function licker(id){
    var diver=document.getElementsByClassName("web_index")[0].getElementsByTagName("div");
    for(var i=0;i<diver.length;i++){ 
        if(i==id){
            diver[i].style.display='block';
        } else {
            diver[i].style.display='none';
        }   
    }
}​

JSFiddle Example

答案 1 :(得分:1)

试试这个

<ul>
   <li onclick="licker(this);">the first li</li>
   <li onclick="licker(this);">the second li</li>
   <li onclick="licker(this);">the third li</li>
</ul>
<div class="web_index">
   <div style="display: block">content one</div>
   <div style="display: none">content two</div>
   <div style="display: none">content three</div>

function licker(sender) {
    var lier = document.getElementsByTagName("li");
    var diver = document.getElementsByClassName("web_index")[0].getElementsByTagName("div");
    for (var i = 0; i < lier.length; i++) {
       if (lier[i] != sender) continue;
       for (j = 0; j < diver.length; j++) {
          if (i == j)
             diver[j].style.display = 'block';
          else 
              diver[j].style.display = 'none';

          }
       }
    }
</script>