如何使用jQuery切换点击按钮

时间:2019-01-23 04:22:59

标签: jquery css

在我的应用程序中,我有一个箭头按钮,当用户首次进入页面时,单击该按钮时他可以看到一个向下箭头。我需要在再次单击该图像时将其图像更改为向上箭头。向下箭头我该怎么做

<button type="button" id="btnfilterparameters" class="buttonFilter primaryColor">
  <span class="f18">
    <i class="fa fa-angle-double-down" aria-hidden="true"></i>
  </span>
  Search
</button>

$("#btnfilterparameters").click(function() {
  $(this).toggleClass("buttonActive"); //here i need to change the arrows on click
  if ($(this).hasClass("buttonActive")) { //here i need to change the arrows on click

  } else {

  }
});

2 个答案:

答案 0 :(得分:1)

$(this).find('span.fa')将在按钮元素内找到跨度

$("#btnfilterparameters").click(function () {
  $(this).find('span i.fa').toggleClass('fa-angle-double-up fa-angle-double-down');
});

提琴:https://jsbin.com/noqirutexe/edit?html,js,output

引用:

答案 1 :(得分:0)

$("#btnfilterparameters").click(function () {
 if($(this).hasClass('btn-success')){
    $(this).removeClass('btn-success').addClass('btn-warning');
    $(this).find('i').removeClass('fa fa-angle-double-down')
    .addClass('fa fa-angle-double-up');
    console.log('set btn-warning')
  }else if($(this).hasClass('btn-warning')){
    $(this).removeClass('btn-warning').addClass('btn-success');
    $(this).find('i').removeClass('fa fa-angle-double-up')
    .addClass('fa fa-angle-double-down');
    console.log('set btn-success')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>


<button id="btnfilterparameters" class="btn btn-success">click me
<i class="fa fa-angle-double-down"></i> </button>

您可以使用javascript的hasclass(),addclass()和removeClass()函数。

$("#btnfilterparameters").click(function () {
  $(this).find('span.fa').toggleClass('fa-angle-double-up fa-angle-double-down');
 if($(this).hasClass('fa-angle-double-up')){
    $(this).removeClass('fa-angle-double-up');
    $(this).addClass('fa-angle-double-down');
  }
});