如何在自定义列表组的点击事件中添加活动类?

时间:2019-06-13 06:36:45

标签: javascript reactjs twitter-bootstrap

以下是我的自定义列表组的代码。单击项目列表后,如何添加活动课程。

<div class="list-group">
  <a href="#!" class="list-group-item list-group-item-action flex-column align-items-start active">
    <div class="d-flex w-100 justify-content-between">
      <h5 class="mb-2 h5">List group item heading</h5>
      <small>3 days ago</small>
    </div>
    <p class="mb-2">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius
      blandit.</p>
    <small>Donec id elit non mi porta.</small>
  </a>
  <a href="#!" class="list-group-item list-group-item-action flex-column align-items-start">
    <div class="d-flex w-100 justify-content-between">
      <h5 class="mb-2 h5">List group item heading</h5>
      <small class="text-muted">3 days ago</small>
    </div>
    <p class="mb-2">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius
      blandit.</p>
    <small class="text-muted">Donec id elit non mi porta.</small>
  </a>
  <a href="#!" class="list-group-item list-group-item-action flex-column align-items-start">
    <div class="d-flex w-100 justify-content-between">
      <h5 class="mb-2 h5">List group item heading</h5>
      <small class="text-muted">3 days ago</small>
    </div>
    <p class="mb-2">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius
      blandit.</p>
    <small class="text-muted">Donec id elit non mi porta.</small>
  </a>
</div>

尽管这将在我的react-app中,但jquery中的解决方案对我来说很好。

1 个答案:

答案 0 :(得分:1)

您可以通过将处理程序添加到list-group-item类的click事件中来实现

以下应该可以工作

$(".list-group-item").click(function(){

   var listItems = $(".list-group-item"); //Select all list items

   //Remove 'active' tag for all list items
   for (let i = 0; i < listItems.length; i++) {                    
      listItems[i].classList.remove("active");
   }

   //Add 'active' tag for currently selected item
   this.classList.add("active");
});