2012-04-18 26 views
-1

我有一段時間在客戶端的下拉菜單上工作。我認爲我的代碼太複雜了。我需要一個解決方案/替代方法來執行既定目標。HTML/JS簡化

<font id="l1b" size="4" color="black" style="cursor:pointer; color:black;" 
    onclick="showSubMenu('cat2'); 
    document.getElementById('cat1').style.display = 'none'; 
    document.getElementById('cat3').style.display = 'none'; 
    document.getElementById('cat4').style.display = 'none'; 
    document.getElementById('pa1').style.display = 'none'; 
    document.getElementById('pb1').style.display = 'none'; 
    document.getElementById('pc1').style.display = 'none'; 
    document.getElementById('pd1').style.display = 'none'; 
    document.getElementById('pa2').style.display = 'none'; 
    document.getElementById('pb2').style.display = 'none'; 
    document.getElementById('pc2').style.display = 'none'; 
    document.getElementById('pd2').style.display = 'none'; 
    document.getElementById('da2a').style.display = 'none'; 
    document.getElementById('da2b').style.display = 'none'; 
    document.getElementById('da2c').style.display = 'none'; 
    document.getElementById('da2d').style.display = 'none'; 
    document.getElementById('da2e').style.display = 'none'; 
    document.getElementById('da2f').style.display = 'none'; 
    document.getElementById('da2g').style.display = 'none'; 
    document.getElementById('da2h').style.display = 'none';">Tea Bags<img src="arrow.png" style="position:relative; left:8px; top:3px;"></font> 

這裏的概念的圖:http://robstest.mydnd.com/helppic.php

第一人幫忙指點10加分! :D

+0

你可能有更好的運氣比上http://codereview.stackexchange.com。 – 2012-04-18 03:44:36

+1

是不是有沒有使用jQuery來加快速度的原因?然後,您可以循環顯示ID列表並將顯示設置爲無。還有很多提供UI功能的jQuery插件,例如下拉菜單。 – arboc7 2012-04-18 03:45:03

+2

Woah,一個字體標籤。有一段時間沒有見過他們。 – 2012-04-18 03:55:08

回答

0

獲取子元素並遍歷它們,設置每個元素的顯示。將其填充到諸如yourfunction(parentDiv)之類的函數中,並在分號後應用於單擊事件。

我會輸入這段代碼,但現在我沒有足夠的材料可以使用。

+0

老兄,如果我要把你的源代碼發給你,你認爲你能幫助我嗎? – 2012-04-18 23:13:27

2

爲了說明使用庫如jQuery的好處,讓您的生活更輕鬆:

純JavaScript

var elementList = ['cat1', 'cat2', 'cat3', 'cat4', 'pa1', ... , 'da2h']; 
function showSubMenu(el) { 
    for (var i = 0; i < elementList.length; i++) { 
     if (elementList[i] != el) { 
      document.getElementById(elementList[i]).style.display = 'none'; 
     } 
    } 
} 

jQuery的

var elementList = ['cat1', 'cat2', 'cat3', 'cat4', 'pa1', ... , 'da2h']; 
function showSubMenu(el) { 
    $.each(elementList, function() { 
     if (this != el) { 
      $('#' + this).css({display: "none"}); 
     } 
    } 
} 

本教程還可能有幫助:http://www.html-5-tutorial.com/

0

使用jQuery做這樣的事情:

$(function() { 
    $("#l1b").children().each(function() { 
     $(this).hide(); 
    }); 
}); 
+0

這看起來並不像他試圖隱藏'l1b'的孩子。我認爲他們是兄弟姐妹... – arboc7 2012-04-18 16:24:13

1

這裏是一個jQuery下拉教程鏈接,做類似的東西你想要什麼:

http://css-tricks.com/simple-jquery-dropdowns/

你...也可以下載文件並根據需要進行修改。

這對你來說是一個很好的練習,可以在你製作項目時玩耍並學習。

(另外,你可能想看看在下拉菜單中的一些其他實現以獲得最佳實踐的想法 - 你嘲笑了UI看起來有點混亂,爲最終用戶)