基于按钮的Div显示

div display based on button

本文关键字:Div 显示 按钮 于按钮      更新时间:2023-09-26

我在下面有一个jsfield:

http://jsfiddle.net/Jsh2V/10/

第一组测试按钮("显示它"answers"隐藏它")效果很好。我一直试图让第二组按钮("拥有它"answers"需要它")与div做同样的事情。不工作。有什么建议吗?还有,如果有更有效的方法…

下面是来自小提琴的代码:

<!DOCTYPE html>
<html>
<head>
  <style>
      p { background:yellow; }
      </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button class="1">Show it</button>
  <button class="2">Hide it</button>
      <p style="display: none" class="1">Hello</p>
      <p style="display: none" class="2">Un Hello!</p>
<script>
    $("button.1").click(function () {
    $("p.1").show("slow");
    $("p.2").hide("fast");
    });
</script>
<script>
    $("button.2").click(function () {
    $("p.1").hide("fast");
    $("p.2").show("slow");
    });
</script>

    <button class="have">Have</button>
    <button class="need">Need</button>
    <div id="have" style="display: none">HAVE YO</div>
    <div id="need" style="display: none">NEED YO</div>
<script>
    $("button.have").click(function () {
    $("div.have").show("slow");
    $("div.need").hide("fast");
    });
</script>
<script>
    $("button.need").click(function () {
    $("div.need").show("slow");
    $("div.have").hide("fast");
    });
</script>
</body>
</html>

应该是div#have而不是div.have,因为您的div具有have的id,而不是have的类别。

<script>
    $("button.have").click(function () {
    $("div#have").show("slow");
    $("div#need").hide("fast");
    });
</script>
<script>
    $("button.need").click(function () {
    $("div#need").show("slow");
    $("div#have").hide("fast");
    });
</script>

这是一个工作小提琴:

http://jsfiddle.net/SfXVA/

您对第二个div使用了ID,因此您需要使用#(用于ID)来引用它们,而不是。(对于类)在你的选择器。

[编辑]

另外,你不需要做'div#have',只需'#have'就足够了,因为ID在DOM中应该是唯一的。