查找元素并添加类(jQuery) [英] Find element and add class (jQuery)

查看:96
本文介绍了查找元素并添加类(jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<ul>
   <li><a href="#">LEVEL 1</a>
      <ul>
         <li>...</li>
      </ul>
   </li>
   <li><a href="#">LEVEL 1</a>
      <ul>
         <li>...</li>
      </ul>
   </li>
</ul>

我有一个嵌套列表,我想根据以下条件使用jQuery向包含A>LEVEL 1的LI添加类:if a nested UL exists AFTER UL LI A, do x else y.

I have a nested list and I want to use jQuery to add class to the LI that containts A>LEVEL 1 based on this condition: if a nested UL exists AFTER UL LI A, do x else y.

谢谢.

推荐答案

要将类简单地添加到具有锚点后跟<ul><li>元素中,请执行以下操作:

To simply add a class to the <li> elements that have an anchor followed by a <ul> do this:

$("ul li:has(a + ul)").addClass("someClass");

如果您真的需要不同的类来确定是否正确,那么您将需要一些代码:

If you really need different classes on whether it's true then you'll need some code:

$("ul li").each(function() {
  var a = $(this).children("a");
  if (a.next("ul").length > 0) {
    $(this).addClass("first");
  } else {
    $(this).addClass("second");
  }
});

这篇关于查找元素并添加类(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆