jQuery遍历.closest()。find()不起作用? (用jsFiddle)

时间:2014-07-10 01:56:35

标签: jquery html traversal

我希望使用jQuery遍历查找某个div,如果该div有特定的类,则显示警告.. http://jsfiddle.net/gfA4F/1/

这是HTML(外部div用于模板目的):

<div class="thisness">

<div class="container">
    <div class="btn-group dropdown options-btns mark-read">
        <button type="button" class="btn btn-sm options-btn dropdown-toggle" data-toggle="dropdown">
          <span class="glyphicon glyphicon-unchecked"></span>
      </button>
      <ul class="dropdown-menu" role="menu">
        <li>>Item1</li>
        <li>>Item2</li>
        <li>>Item3</li>
      </ul>
    </div>
</div>

<div class="container">
    <div class="btn-group dropdown options-btns mark-read">
        <button type="button" class="btn btn-sm options-btn dropdown-toggle" data-toggle="dropdown">
          <span class="glyphicon glyphicon-check"></span>
      </button>
      <ul class="dropdown-menu" role="menu">
        <li>>Item1</li>
        <li>>Item2</li>
        <li>>Item3</li>
      </ul>
    </div>
</div>

...

</div>

这里的尝试遍历需要纠正:

$(document).ready(function(){

    $(".thisness").on("show.bs.dropdown", ".options-btns", function () {

      var $this = $(this);

      var $that = $this.closest('.container').find('.glyphicon');

      if ($that.hasClass('.glyphicon-unchecked')) {alert('unchecked');}

      else if ($that.hasClass('.glyphicon-check')) {alert('check');}

    });

});

1 个答案:

答案 0 :(得分:2)

无需在.函数中使用hasClass,因为它已在寻找类。

试试这个:

if ($that.hasClass('glyphicon-unchecked')) {
    alert('unchecked');
} else if ($that.hasClass('glyphicon-check')) {
    alert('check');
}

JSFiddle Demo