2016-12-15 98 views
0

我对编码比较陌生,而且我很喜欢手风琴风格的设备我正在努力。为什么这个jQuery显示&隐藏脚本不能按预期工作?

这个想法是有4个div元素和下面他们另一个div。当点击4个div中的一个时,相关文本将显示在框中;点击另一个,第一个div的文本消失,并改变到另一个。点击同样的方块,盒子就消失了。

我的游戏计划:为所有应该隐藏的元素分配相同的类,并将其隐藏在网站上;当单击div时,只显示具有相应ID的元素。

目前,我坚持让它只用一个div工作,我不知道为什么。如果你能告诉我问题在哪里,我将不胜感激。因此

我的代码远(现在只有2 div的,使这个更简洁):

HTML:

<div class="expander" id="first-p">Click this text to see the one below.</div> 
<div class="expander" id="second-p">Another clickable div.</div> 
<div class="concealed" id="concealed-first-p">This is the hidden text.</div> 
<div class="concealed" id="concealed-second-p">This is another hidden text.</div> 

JQUERY:

$(document).ready(function() { 
    $(".concealed").hide();    //hide all elements with class .concealed after site launch 

    $(".expander").click(function(){    //A div which triggers the displaying of the hidden stuff is clicked 


/* If the hidden div is already displayed, hide it instead and call it a day */ 

      if (clickedElement == $(this).attr("id")) { 
       alert ("hide div again"); 
       $("#expandingElement").hide(); 
      } 

/* Show the hidden div */ 

else { 
      $("#expandingElement").hide();    // hide any div that might already be displayed 
      var clickedElement = $(this).attr("id");   // get the ID of the clicked element so we know which correlating one to display afterwards 
      var expandingElement = "concealed-" + clickedElement;   // construct the ID of the element to display 
      alert("Name of expandingElement ID is " + expandingElement);    // this is just an alert so I know the variable was constructed correctly 
      $("#expandingElement").show();    // show the div 
      } 
     }); 
    }); 

到目前为止,代码工作起来直到警报显示正确的变量名称,但该div后来不显示。你能告诉我我做错了什么吗?

另外,我想有更简单的方法来做到这一点,我很乐意在这件事上得到任何帮助。但最重要的是,我想知道为什么代码无法按预期工作。

+1

你的哪个'html'的部分有''id' expandElement' – 2016-12-15 12:01:32

回答

1

好像你已经搞砸了选择:

您的div都不具有ID“expandingElement”但你打电话

$("#expandingElement").hide() 

此尝试应用隐藏()与元素ID expandingElement。但是你想使用名为expandingElement的变量。所以,你需要做的是CONCAT这两个正确:

$("#"+expandingElement).hide() 
+0

感谢您的详细,新手友好的解释! –

+0

不客气。 –

+0

我在看到你和桑迪的回答后立即提出了投票,但由于该网站通知我“记录了名声低于15的人的投票,但不更改公开显示的帖子分数”:/ –

0

您在“”使用ID。所以它被视为string。 你应该使用这样:

$("#" + expandingElement).show();

0

如果我是正确的它似乎是你正在寻找类似的Boostrap's Tabs

你失败的东西是: $( “#expandingElement”)。显示隐藏(); (“#”+ expandingElement).show()/ hide();();();}}

expandingElement是一个变量,所以如果你在btwn中插入它,它就会变成一个字符串。

总之:

$(document).ready(function() { 
    $(".concealed").hide();  

    $(".expander").click(function(){    
     $(".concealed").hide(); 
     var clickedElement = $(this).attr("id"); 

     var expandingElement = "concealed-" + clickedElement;    

     $("#"+expandingElement).show();  

     }); 
    }); 
相关问题