首页 > 解决方案 > 在 div、jquery 中隐藏和显示特定文本

问题描述

我在隐藏和显示特定文本时遇到问题,特别是“picked”和“show_hidden”。在这个任务中,我必须使被选中的隐藏然后能够单击“应该”以再次显示被选中的东西。任何帮助将不胜感激:)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Coding Tasks</title>

    <script src="jquery.js"></script>
    <script>
    $(document).ready(function(){
      $("a").click(function() {
        $("#picked").toggle();
       });
      });
      $("a").click(function() {
        $("#show_hidden").toggle();

    });
  </script>
    <style>
        .important {
          font-weight: bold;
          font-size: xx-large;
        }
        .set_colour {
          color: blue;
        }
        .test
        {
            width: 500px;
        }
        div
        {
            padding-top: 3px; padding-right: 3px; padding-bottom: 3px; padding-left: 3px; margin-top: 3px; margin-right: 3px; margin-bottom: 3px; margin-left: 3px; border-top-color: navy; border-right-color: navy; border-bottom-color: navy; border-left-color: navy; border-top-width: thin; border-right-width: thin; border-bottom-width: thin; border-left-width: thin; border-left-style: solid; border-right-style: solid; border-top-style: solid; border-bottom-style: solid; height:200px;
        }
    </style>

</head>
<body>
<p>Name: George Bob</p>

  <div>
  <p class="test">Test 1: Hide and Show</p>
   <p class="picked">When you click on <a href="#">this</a> all paragraphs of class 'picked' should take 1.5sec and hide</p>
   <p id="show_hidden"><a href="#">Should</a> should not hide and on click should show hidden</p>
   <p class="picked">This should hide as well</p>
  </div>

</body>
</html>

标签: htmljquery

解决方案


You seem to have defined you 'picked' elements with a class, yet you selected them using an id.

You should update your selector this way:

$(".picked").toggle(); // select by class, not id

Another issue with your code is that both anchors are selected by the element type (i.e. a). This way there is no way to distinguish between the elements.

You can give them individual id's and then use those to select the appropriate element for showing / hiding other elements.

That is, you should define your anchors in a similar way to this:

<a id="hide-link" href="#">this</a>

and the second one:

<a id="show-link" href="#">Should</a>

Finally, you script should look like this:

$(document).ready(function(){
    $("#hide-link").click(function() {
        $(".picked").hide();
    });

    $("#show-link").click(function() {
        $(".picked").show();
    });
});

Hope this helps.


推荐阅读