2011-12-02 190 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