具有DIV切换规范的功能

时间:2011-11-09 23:03:39

标签: jquery jquery-selectors

我只想在点击一个按钮时显示div,并在单击另一个按钮时关闭它。我有下面的代码但是当我将它添加到页面时,除了按钮之外,一切都消失了。我如何才能让它成为一个特定的DIV。

<style>
  div { background:#def3ca; margin:3px; width:80px; 
  display:none; float:left; text-align:center; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

  <button id="showr">Show</button>
  <button id="hidr">Hide</button>
  <div>Hello 3,</div>

  <div>how</div>
  <div>are</div>
  <div>you?</div>
<script>
$("#showr").click(function () {
  $("div:eq(0)").show("fast", function () {
    /* use callee so don't have to name the function */
    $(this).next("div").show("fast", arguments.callee);
  });
});
$("#hidr").click(function () {
  $("div").hide(2000);
});

</script>

3 个答案:

答案 0 :(得分:0)

一切都消失的原因是因为你告诉它!在您的CSS中,您的所有div规则都是display: none;(不可见)。

相反,您只希望最初隐藏的div具有display: none;内嵌样式

即。将您的CSS更改为:

<style>
  div { background:#def3ca; margin:3px; width:80px; 
  float:left; text-align:center; }
  </style>

和你的divs:

  <div style="display: none;">Hello 3,</div>

  <div>how</div>
  <div>are</div>
  <div>you?</div>

答案 1 :(得分:0)

我认为问题是你在#showr的回调函数中再次显示,而在#hidr点击你只是隐藏所有的div。看看这个似乎做你需要的小提琴:

http://jsfiddle.net/VdUdE/

基本上我只是根据你点击的按钮并显示/隐藏它来选择第一个/最后一个隐藏/可见元素。代码:

$("#showr").click(function () {
    $(this).siblings("div:hidden:first").show("fast");

});
$("#hidr").click(function () {
    $(this).siblings("div:visible:last").hide("fast");
});

答案 2 :(得分:-1)

我这是你要找的?

<style>
  div { background:#def3ca; margin:3px; width:80px; 
  display:none; float:left; text-align:center; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

  <button id="showr">Show</button>
  <button id="hidr">Hide</button>
  <div id="1">Hello 3,</div>

  <div id="2">how</div>
  <div id="3">are</div>
  <div id="4">you?</div>
<script>
    var Counter = 0;
$("#showr").click(function () {
    Counter = Counter + 1;
    if(Counter > 4){ Counter = 4;}
  $('#'+Counter).show("fast", function () {

  });

});
$("#hidr").click(function () {
  $("#"+Counter).hide(2000);
     If(Counter > 0 ) 
         Counter = Counter -1;

});

</script>

测试链接 http://jsfiddle.net/fPfvg/

相关问题