在第一次单击打开下拉菜单的按钮时更改类

Change Class on first click of a button that opens a dropdown menu?

本文关键字:按钮 下拉菜单 第一次 单击      更新时间:2023-09-26

我希望有一个按钮的图标类更改仅在按钮事件的第一次点击,这也将ajax .put一个字段到数据库.

<div class="btn-group check-btns checkIt">
    <button type="button" class="btn btn-xs dropdown-toggle" data-toggle="dropdown">
    <span class="glyphicon glyphicon-unchecked"></span>
    </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">List Item 1</a></li>
    </ul>
</div>

测试了这个简单的。先点击(http://jsfiddle.net/57268/1/),但认为Bootstrap内置的下拉。open class开关可能会防止这种情况发生。

$(document).ready(function () {
    $(function () {
    $('.checkIt').on('click', function () {

但是将其更改为收听正在显示的下拉菜单还没有工作http://jsfiddle.net/57268/:

$(document).ready(function () {
    $(function () {
    $('.btn-group.check-btns.checkIt').on('show.bs.dropdown', function () {
            console.log('checkIt clicked');
            var $this = $(this);
          var $that = $(this).children('.check-btns').children('.btn').find('.glyphicon')
          if ($that.hasClass('.glyphicon-unchecked')) {
            $that.removeClass('.glyphicon-unchecked').addClass('.glyphicon-check');
            console.log('now checked icon');
            $this.removeClass('.checkIt').addClass('.checkedIt');
            console.log('now checkedIt class');
            alert('checked and checkedIt .. now an ajax .put call');
          }
      })
    });
});

Try

小提琴演示

hasClass, removeClass, addClass取className非选择器

$el.addClass('class')正确,$el.addClass('.class')不正确

$(document).ready(function () {
    $('.checkIt').on('click', function () {
        console.log('checkIt clicked');
        var $this = $(this),
            $that = $(this).find('.glyphicon'); //changed to .find() only
        if ($that.hasClass('glyphicon-unchecked')) {
            $that.removeClass('glyphicon-unchecked').addClass('glyphicon-check');
            console.log('now checked icon');
            $this.removeClass('checkIt').addClass('checkedIt');
            console.log('now checkedIt class');
            alert('checked and checkedIt');
        }
    });
});

要解释Tushar的解决方案,您的原始代码有两个问题:

  1. 用于定义$的链使用了.children('.check-btns') -这在$this元素子元素中查找类为check-btns的元素,但$this实际上是已经有这个类的div(您正在查找的元素在它自己的子元素中)

  2. 在hasClass中,您正在寻找class "。

  3. -这是不正确的,类名实际上是"glyphicon-unchecked",点只在需要选择器时使用。