通过JQuery在父<li>中查找.class

时间:2015-12-23 05:51:50

标签: jquery jquery-selectors

<!--HTML-->
<ul class="navigation">
    <li>
        <a class="handle-link" href=""><img src=""/>Dashboard</a>
    </li>

    <li class="active">
        <a href="#" class="expand"><img src=""/>Multiple</a>
        <ul>
            <li class="current">
                <a class="handle-link sub-menu" href="">One</a>
            </li>
            <li>
                <a class="handle-link sub-menu" href="">Two</a>
            </li>   
            <li>
                <a class="handle-link sub-menu" href="">Three</a>
            </li>
        </ul>
    </li>
    <li >
        <a class="handle-link" href=""><img src=""/>Single</a>
    </li>
</ul>


    $('a.handle-link').click(function (e) {
        e.preventDefault();
        var currentMenuItem = $(this);
        var parentLI = $(currentMenuItem).closest('li');

        if ($(currentMenuItem).hasClass('sub-menu')) {
            if ($(parentLI.hasClass('current'))) {
                alert('This is current');
            }
            else {
                //Error here- 
                alert('This is not current'); //This is not executing
            }
        }
        else {
            alert('this is somewhere else.');
        }
    });

当我点击“Two”时,它也会返回“This is current”。但它应该返回“这不是最新的”。

任何帮助?

3 个答案:

答案 0 :(得分:1)

问题出在你的if语句中,因为你传递了一个jQuery对象($(parentLI.hasClass('current'))),它总是很简单。

所以只需删除包装$()调用,以便hasClass语句评估if返回的值

 if (parentLI.hasClass('current')) {
   alert('This is current');
 } else {
   //Error here- 
   alert('This is not current'); //This is not executing
 }

答案 1 :(得分:0)

因为返回了jQuery对象,所以

$(parentLI.hasClass('current'))总是很简单。你需要摆脱包裹$()

if (parentLI.hasClass('current')) { ...

答案 2 :(得分:0)

试试这个:

$('a.handle-link').click(function (e) {
  e.preventDefault();
  var currentMenuItem = $(this);
  var parentLI = currentMenuItem.parent('li');

  if (currentMenuItem.hasClass('sub-menu')) {
      if (parentLI.hasClass('current')) {
          alert('This is current');
      } else {
          alert('This is not current');
      }
    } else {
        alert('this is somewhere else.');
    }
});

WORKING FIDDLE