jQuery将类添加到某些元素 [英] jQuery add class to certain elements

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

问题描述

我有一个这样的多级菜单:

I have a multilevel menu like this :

<ul>
  <li>item 1
    <ul>
      <li>item 1.1</li>
      <li>item 1.2</li>
    </ul>
  </li>
  <li>item 2</li>
  <li>item 3
    <ul>
      <li>item 3.1</li>
      <li>item 3.2</li>
    </ul>
  </li>
  <li>item 4</li>
</ul>

在jQuery中我有

$("#divId ul li:odd").addClass("blue");
$("#divId ul li:even").addClass("green");

问题是jQuery将类添加到所有列表中。
我希望jQuery只将类添加到第一级(ul> li.class)而不是内部子级(ul> li> ul> li.class)

The problem is that jQuery adds the class to all the lists. I would like jQuery to just add the class to the first level (ul > li.class) and NOT the inner childs (ul > li > ul > li.class)

谢谢

推荐答案

这应该有效:

$("#divId ul:first > li:odd").addClass("blue"); 
$("#divId ul:first > li:even").addClass("green"); 

它会将类添加到divId中找到的第一个ul标记的子代。

It will add the classes to the children of the first ul tag found in divId.

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

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