首页 > 解决方案 > 如何选择点击的内容?

问题描述

如何选择点击的内容?现在我正在制作一个系统,当我点击一个按钮时,数据显示在 nav 标签中。我在views.py中写了代码

class TopView(TemplateView):
    model = Data
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['data'] = Data.objects.all()
        return context

当我点击一个按钮时,所有数据都显示在 index.html 的 nav 标签中。我只想在 nav 标签中显示点击的数据。我想我是这样写的,但是我的代码有什么问题?我应该如何解决这个问题?

<html lang="ja">
    <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<head>
    <meta charset="UTF-8">
    <title>HOMEPAGE</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
   nav {
    width: 312px;
    height: 100%;
    transition: all 0.2s;
    transform: translate(312px);
    position: fixed;
    top: 0;
    right: 0;
    z-index: 1000;
    background-color: #FFF;
   }
   nav.open {
    transform: translate(0);
   }
  </style>
</head>

<script>
$(function(){
  $('.btn_menu').click(function(){
    $(this).next('nav').toggleClass('open');
  });
})
</script>
<body>

    <section id="center">
                        <button type="button" class="btn_menu">
                            AAA
                        </button>
                        <button type="button" class="btn_menu">
                            BBB
                        </button>
                        <button type="button" class="btn_menu">
                            CCC
                        </button>

    </section>

    <nav>
        <h2>HOMEPAGE</h2>
        <!---->
                <h4>AAA</h4>
                <p>aaa</p>
        <!---->
                <h4>BBB</h4>
                <p>bbb</p>
        <!---->
                <h4>CCC</h4>
                <p>ccc</p>
        <!---->
    </nav>

</body>
</html>

标签: pythonjqueryhtmldjango

解决方案


看到您呈现的 HTML 后,您需要执行以下操作:-

$(document).ready(function(){
  $('nav h4, nav p').hide();
  $('.btn_menu').click(function(){
    var obj = $(this);
    $('nav h4, nav p').hide();
    $('h4, p').each(function(){
      if($.trim($(this).text().toLowerCase()) == $.trim(obj.text().toLowerCase())){
        $(this).show();
      }
    });
  });
});

工作片段: -

$(document).ready(function(){
  $('nav h4, nav p').hide();
  $('.btn_menu').click(function(){
    var obj = $(this);
    $('nav h4, nav p').hide();
    $('h4, p').each(function(){
      if($.trim($(this).text().toLowerCase()) == $.trim(obj.text().toLowerCase())){
        $(this).show();
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="center">
  <button type="button" class="btn_menu">
      AAA
  </button>
  <button type="button" class="btn_menu">
      BBB
  </button>
  <button type="button" class="btn_menu">
      CCC
  </button>

</section>

<nav>
<h2>HOMEPAGE</h2>
<!---->
  <h4>AAA</h4>
  <p>aaa</p>
<!---->
  <h4>BBB</h4>
  <p>bbb</p>
<!---->
  <h4>CCC</h4>
  <p>ccc</p>
<!---->
</nav>


推荐阅读