简体   繁体   English

从元素数组中查找哪个元素具有特定类的更好方法

[英]Better way to Find which element has a specific class from an array of elements

Suppose I have a List like the following 假设我有一个类似以下的列表

  <ul>
     <li id="slide-a" class="slide-li active-slide"><a href="#" >A</a></li>
     <li id="slide-b" class="slide-li"><a href="#" >B</a></li>
     <li id="slide-c" class="slide-li"><a href="#" >C</a></li                        
  </ul>

Now , using Jquery I wanna Find out which Element has the class 'active-class' . 现在,我想使用Jquery找出哪个Element具有'active-class' One way would to have a nested if statement something like this: 一种方法是嵌套if语句,如下所示:

if($("#slide-a").hasClass('active-slide'))
{
  active = 'slide-a';
}
else
{
  if($("#slide-b").hasClass('active-slide'))
  {
    active = 'slide-b';
  }
  else
  {
    if($("#slide-c").hasClass('active-slide'))
    {
      active = 'slide-c';
    }
  }
}

My question is if there exists any way to optimize the code above. 我的问题是是否有任何方法可以优化上面的代码。 Is there a generic way to achieve this such that even if I add 10 more li's in the ul the code just works fine without any modification. 有没有一种通用的方法可以做到这一点,即使我在ul中再增加10个li,代码也可以正常工作而无需任何修改。

Maybe just 也许就是

var active = $(".active-slide").attr("id");

Demo 演示版

Use Attribute starts with selector and .each() . Use Attribute starts with selector.each() Attribute starts with selector Try this: 尝试这个:

$(document).ready(function(){
    $('li[id^=slide]').each(function(){
        if($(this).hasClass('active-slide'))
            alert($(this).attr('id'));
    });
});

DEMO 演示

If you have more than one li with class active-slide use this: 如果您的active-slide类有多个li,请使用以下命令:

$(document).ready(function(){
    var idVal = [];
    $('li[id^=slide]').each(function(){
        if($(this).hasClass('active-slide'))
            idVal.push($(this).attr('id'));
    });
    console.log(idVal);
});

DEMO 演示

You could a use jQuery $.each() on the ul to iterate through. 您可以在ul上使用jQuery $ .each()进行迭代。

fiddle coming in a second. 提琴来一秒钟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM