Javascript jQuery - 找到一个存在的类并返回真/假

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14887055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:14:16  来源:igfitidea点击:

jQuery - find a class exist and return true/false

javascriptjqueryfind

提问by user007

I want to check if class exists inside a child of liand if class exists return trueor defined.

我想检查类是否存在于 的子项中li以及类是否存在返回truedefined

HTML

HTML

<li class="show-more">
<a> if found selected then add to this</a>
<ul>
<li><a> sub-menu</a></li>
<li><a> sub-menu</a></li>
<li><a class="selected"> sub-menu</a></li>
<li><a> sub-menu</a></li>
</ul>
</li>

here is my code, but wont return true or false, it return the url of anchor

这是我的代码,但不会返回 true 或 false,它返回锚点的 url

var active_sub_menu = $('li.show-more ul li').find('selected');

alert(active_sub_menu);
if(typeof active_sub_menu == 'defined'){
    $('li.show-more > a').addClass('selected');
}

please dont suggest to use CSS, I just need javascript

请不要建议使用 CSS,我只需要 javascript

回答by Roko C. Buljan

Why not simply go for .hasClass()or length:

为什么不简单地选择.hasClass()or length

if ( $("selector").length ) {   /*EXISTS (greater than 0) */  }

or

或者

if ( $("selector")[0] ) {   /*EXISTS (not undefined) */  }

or

或者

if ( $("selector").hasClass("someClass") ) {   /*EXISTS (has class) */  }

$('.show-more').each(function () {

  if ( $(this).find("li a.seleted").length ) {
    console.log('FOUND');
    $(this).children("a").addClass('selected'); // Make main anchor  also selected 
  } else {
    console.log('NOT FOUND');
  }

});
.selected {
  background: red;
}
<ul>
  <li class="show-more">
    <a> if found .selected then add also to this anchor</a>
    <ul>
      <li><a> sub-menu</a></li>
      <li><a> sub-menu</a></li>
      <li><a class="selected"> sub-menu</a></li>
      <li><a> sub-menu</a></li>
    </ul>
  </li>
</ul>


<script src="//code.jquery.com/jquery-3.1.0.js"></script>

回答by bfavaretto

if($('li.show-more ul li').hasClass('defined')) {
    $('li.show-more > a').addClass('selected');
}

I assume that's what you intended with typeof?

我想这就是你的意图typeof

Another option:

另外一个选项:

var active_sub_menu = $('li.show-more ul li').find('.selected');
if(active_sub_menu.length) {
    $('li.show-more > a').addClass('selected');
}

回答by charlietfl

use lengthto test if selector returns elements

用于length测试选择器是否返回元素

if( $('li.show-more ul li').find('selected').length){
   $('li.show-more > a').addClass('selected');
}