【发布时间】:2014-12-18 20:24:45
【问题描述】:
所以,我有一个这样的网页。三个按钮在 div 之间切换,并且没有太多代码。但是如果我有 15 个 div 可以切换,就会有更多的代码。有什么办法可以让我的 JS 代码更简单?
<!DOCTYPE>
<html>
<head>
<style type="text/css">
.info {
width: 400px;
height: 580px;
margin: 40px;
float: right;
}
</style>
</head>
<body>
<div class="info" id="swapper-first" style="display:block; border:2px dashed red; padding:25px;">
<p style="margin:0; color:red;">
Red div
</p>
</div>
<div class="info" id="swapper-second" style="display:none; border:2px dotted blue; padding:25px;">
<p style="margin:0; color:blue;">
Blue div
</p>
</div>
<div class="info" id="swapper-third" style="display:none; border:2px solid green; padding:25px;">
<p style="margin:0; color:green;">
Green div
</p>
</div>
<p style="text-align:center; font-weight:bold;">
<a href="javascript:mred('swapper-first','swapper-second', 'swapper-third')">Red</a>
<a href="javascript:mblue('swapper-first','swapper-second', 'swapper-third')">Blue</a>
<a href="javascript:mgreen('swapper-first','swapper-second', 'swapper-third')">Green</a>
</p>
<script type="text/javascript">
function mred(div1,div2,div3) {
d1 = document.getElementById(div1);
d2 = document.getElementById(div2);
d3 = document.getElementById(div3);
d1.style.display = "block";
d2.style.display = "none";
d3.style.display = "none";
}
function mblue(div1,div2,div3) {
d1 = document.getElementById(div1);
d2 = document.getElementById(div2);
d3 = document.getElementById(div3);
d1.style.display = "none";
d2.style.display = "block";
d3.style.display = "none"
}
function mgreen(div1,div2,div3) {
d1 = document.getElementById(div1);
d2 = document.getElementById(div2);
d3 = document.getElementById(div3);
d1.style.display = "none";
d2.style.display = "none";
d3.style.display = "block"
}
</script>
</body>
</html>
【问题讨论】:
-
你会用JQuery吗?这将简化很多。
-
我建议将此问题移至Code Review,因为它更多的是对您的代码的评估,而不是尝试解决错误和使用困难的算法。
-
我认为您不是在寻找
switch-statement。而不是for循环。
标签: javascript html switch-statement