所以,我有一個這樣的網頁。三個按鈕在divs之間切換,並沒有太多的代碼。但是如果我有15個div來切換,將會有更多的代碼。有什麼辦法讓我的JS代碼更簡單嗎?使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?這將簡化很多這個。 – Matt
我建議將此問題移到[代碼評論](http://codereview.stackexchange.com/),因爲它更像是對代碼的評估,而不是試圖解決錯誤和使用困難的算法。 – SirPython
我不認爲你正在尋找'switch'語句。而不是'for'循環。 – Bergi