2011-12-02 146 views
0

我有問題顯示一個div,然後隱藏前面的div。顯示/隱藏div使用jquery

var newElem = '#ID' + numVariable; 
$('.elemPropGlobal').hide(); 

$(newElem).click(function(){ 
    $('.elemPropGlobal').hide(); 

    $($(this).attr('id') + 'Properties').show(); 

} 

Div時,我點擊

<div class="something" id="ID1" > some data</div> 
<div class="something" id="ID2" > some data</div> 

的div應該顯示和隱藏

<div class="elemPropGlobal" id="ID1Properties" > 

<div class="elemPropGlobal" id="ID2Properties" > 

回答

4

你忘了#

$('#' + this.id + 'Properties').show(); 
0

目前你正在尋找那些元素命名爲ID1Properties等你需要一個#前綴通過ID進行搜索!

$("#" + $(this).attr('id') + 'Properties').show(); 
0

我不知道這是否是一個過於簡單化,但你不能兩個div的設置點擊事件,你的第二選擇遺忘哈希:

$(newElem).click(function(){}); //newElem is #ID1 or #ID2 

你可以做

$(".something").click(function(){ 
     $('.elemPropGlobal').hide(); 

     $("#" + $(this).attr('id') + 'Properties').show(); //Remember the hash! 
    }); 
+0

我想將300行代碼煮成一個例子。我在那裏有#並且應該添加到示例中。點擊事件都有numVariable(var newElem ='#ID'+ numVariable; )。我試圖找到和優雅的方式來顯示隱藏,並希望確保我使用的代碼是最佳實踐。 – user1009749

+0

我這麼認爲,這只是萬一。檢查丟失的哈希雖然:) – NicoSantangelo