如何将样式应用于JQuery数组中的特定元素 [英] How to apply style to a specific element in JQuery array

查看:42
本文介绍了如何将样式应用于JQuery数组中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习JQuery的基础知识,但不能解决此问题:给定3个绿色的<li>元素会将1st和3rd元素变成红色,将2nd元素变成橙色.

代码:

I am learning the basics of JQuery, and can't solve this problem: given 3 green <li> elements turn 1-st and 3-rd elements to red color, and the 2-nd element to orange.

<!DOCTYPE html>
<html>
  <head>
    <title>element</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <style type="text/css" media="screen">
      ul li{color: green;}
    </style>
  </head>
  <body>
    <ul>
      <li>text 1</li>
      <li>text 2</li>
      <li>text 3</li>
    </ul>
    <script>
      var lis = $("ul li").css("color", "red");
    </script>
  </body>
</html>

我能够将所有元素设置为红色,但不能将第二个元素设置为橙色:lis[1].css("color", "orange");不起作用.

I was able to make all the elements red, but I can't make the 2-nd orange: lis[1].css("color", "orange"); doesn't work.

推荐答案

您正在DOM对象而不是jQuery对象上调用css,因为索引器[]为您提供了DOM对象.您需要

You are calling css on DOM object instead of jQuery object as indexer [] gives you DOM object You need eq() instead of indexer

实时演示

Live Demo

lis.eq(1).css("color", "orange");

说明:将匹配的元素集减少到 指定的索引.

Description: Reduce the set of matched elements to the one at the specified index.

您还可以直接在选择器中使用:eq()

You can also use :eq() directly in the selector

$("ul li:eq(1)").css("color", "red");

这篇关于如何将样式应用于JQuery数组中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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