我正在学习 JQuery 的基础知识,无法解决这个问题: given 3 green <li>
元素将第 1 和第 3 元素变为红色,将第 2 元素变为橙色。
代码:
<!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");
不起作用。
最佳答案
你在 DOM 对象上调用 css 而不是 jQuery 对象,因为索引器 []
给你 DOM 对象你需要 eq()而不是索引器
lis.eq(1).css("color", "orange");
Description: Reduce the set of matched elements to the one at the specified index.
您还可以使用 :eq()直接在选择器中
$("ul li:eq(1)").css("color", "red");
关于javascript - 如何将样式应用于 JQuery 数组中的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23057914/