使用class.onclick更改glyphicon

时间:2018-10-18 13:24:05

标签: javascript jquery

我想知道当我单击HTML按钮时如何更改引导glyphicon。

这是我的按钮:

<button class="btn btn-default btn-choice" type="button" data-toggle="collapse" data-target="#title"
                    aria-expanded="false" aria-controls="title">
              <span class="glyphicon glyphicon-chevron-down"></span> {% trans 'Title' %} </button>

这是我的JavaScript部分:

<script>
  $(document).ready(function () {
    $('.button-choice').click(function () {
      $(this).toggleClass("glyphicon-chevron-down").toggleClass("glyphicon-chevron-up");
    });
  });
</script>

我没有克服单击按钮并在其中更换glyphicon的问题。

3 个答案:

答案 0 :(得分:1)

您的代码似乎是正确的方法。但是,您正在监听错误的类上的click事件:

$(".button-choice") 

代替

$(".btn-choice")

编辑:

您还应该找到跨度到您的按钮中。还有一件事,您可以通过一个呼叫切换多个类:

toggleClass()

答案 1 :(得分:1)

首先,您有一个错字(.button-choice,而不是.btn-choice)。

然后,您需要找到最接近的span并对其进行更新,否则该类将应用于button而不是内部span,并且将无法正常工作

<!-- 
  Bootstrap docs: https://getbootstrap.com/docs
-->

<button class="btn btn-default btn-choice" type="button" data-toggle="collapse" data-target="#title"
                    aria-expanded="false" aria-controls="title">
              <span class="glyphicon glyphicon-chevron-down"></span> {% trans 'Title' %} </button>

js:

$('.btn-choice').click(function () {
  $(this).find('span').toggleClass("glyphicon-chevron-down").toggleClass("glyphicon-chevron-up");
        //^----------^---- Note this! otherwise it won't work, since it would target $(this), which is the button.
});

您的小提琴,已更新:https://jsfiddle.net/6ae0c1dL/2/

答案 2 :(得分:1)

我将使用一个ID来获取包含glyphicon的跨度。该ID在页面中是唯一的,该解决方案仅适用于1个按钮。一种解决方法是使用一些data-something来调用正确的跨度。

此外,您没有为按钮调用正确的类。

$(document).ready(function () {
    $('.btn-choice').click(function () {
      let spanId = $(this).data("spanid");
      $('#' + spanId).toggleClass("glyphicon-chevron-down glyphicon-chevron-up");
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


<button data-spanid="theGlyphicon1" class="btn btn-default btn-choice" type="button" data-toggle="collapse" data-target="#title" aria-expanded="false" aria-controls="title">
  <span id="theGlyphicon1" class="glyphicon glyphicon-chevron-down"></span>my button 1
</button>

<button data-spanid="theGlyphicon2" class="btn btn-default btn-choice" type="button" data-toggle="collapse" data-target="#title" aria-expanded="false" aria-controls="title">
  <span id="theGlyphicon2" class="glyphicon glyphicon-chevron-down"></span>my button 2
</button>