切换Div Javascript [英] Toggle Div Javascript

查看:142
本文介绍了切换Div Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一些div,当点击链接时,他们需要切换(显示/隐藏)

I have some divs on my page that when a link is clicked they need to toggle (show/hide)

JS

var state = 'none';

function showhide(layer_ref) {
//alert(eval( "document.all." + layer_ref + ".style.display") == "none")

if (document.all) { //IS IE 4 or 5 (or 6 beta)
if(eval( "document.all." + layer_ref + ".style.display") == "none"){
eval( "document.all." + layer_ref + ".style.display = 'block'");
}else{
eval( "document.all." + layer_ref + ".style.display = 'none'");
}

}
if (document.layers) { //IS NETSCAPE 4 or below
if(document.layers[layer_ref].display == none){
document.layers[layer_ref].display = "block";
}else{
document.layers[layer_ref].display = "none";
}
}
if (document.getElementById &&!document.all) {
if(document.getElementById(layer_ref).style.display == "none"){
document.getElementById(layer_ref).style.display = "block";
}else{
document.getElementById(layer_ref).style.display = "none";
}
}
}

HTML

     <div class="faq-row" style="z-index: 976;">
       <span class="itp-title"><a href="#" onclick="showhide('div1');">title</a></span>
        <div id="div1" style="display: none;">divcont</div>
     </div>
     <div class="faq-row" style="z-index: 976;">
       <span class="itp-title"><a href="#" onclick="showhide('div1');">title</a></span>
        <div id="div2" style="display: none;">divcont</div>
     </div>
     <div class="faq-row" style="z-index: 976;">
       <span class="itp-title"><a href="#" onclick="showhide('div1');">title</a></span>
        <div id="div3" style="display: none;">divcont</div>
     </div>

我的问题是,无论什么链接我点击它只切换第一个div? Cany任何人看到哪里错了?
感谢

my problem is that no matter what link i click it only toggles the first div? Cany anybody see where im going wrong? Thanks

推荐答案

您的第一个问题是尝试编写非平凡的crossbrowser JavaScript。如果您使用类似 jQuery 的方法,这将非常简单,非常

Your first issue is trying to write non-trivial crossbrowser JavaScript. This would be much, much simpler if you used something like jQuery.

也就是说,你的问题是你的 onClick 处理程序都指向同一个 id

That said, your issue is that your onClick handlers are all pointing to the same id.

onclick="showhide('div1');"

将这些更改为相关的div id,您应该就可以了。

Change these to the relevant div id's and you should be fine.

如果你使用像jQuery这样的函数,这个函数将是不相关的,你可以做一些像:

If you used something like jQuery, this function would be irrelevant though and you could just do something like:

onclick="$('#div1').toggle()"

这篇关于切换Div Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆