您的位置:首页 > Web前端 > JQuery

JQuery里的子元素过滤选择器,加空格与不加空格的区别

2016-03-08 14:25 633 查看
最近学习jquery,发现它的选择器的写法与css的基本语法很像,加不加空格差别很大。

$(“:first-child)——:first只是返回单个元素,而first-child选择符将为每个父元素匹配第一个子元素。

例如子元素过滤选择器

li:first-child(不加空格),这里的父元素指的是li标签的父元素;

li :first-child(加空格),这时候因为变成了ance desc层次选择器(跟父子选择器类似,只是比其作用域大),所以其父元素指的就是li标签了,但因为li元素没有子元素了,所以这样的表达不对。换成ol则可以。

$(“li:first-child),获取了两个 ul父元素中的第一个li元素,并使用css()方法修改了它们在页面中显示的文字颜色。

<!DOCTYPE html>
<html>
<head>
<title>:first-child子元素过滤选择器</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
<h3>改变每个"蔬菜水果"中第一行的背景色</h3>
<ol>
<li>芹菜</li>
<li>茄子</li>
<li>萝卜</li>
<li>大白菜</li>
<li>西红柿</li>
</ol>
<ol>
<li>橘子</li>
<li>香蕉</li>
<li>葡萄</li>
<li>苹果</li>
<li>西瓜</li>
</ol>

<script type="text/javascript">

$("ol :first-child").css("background-color", "green");
//或用$("li:first-child").css("background-color", "green");
</script>
</body>
</html>




$(“ol :first-child”):中间有空格,ol是父元素,表示ol下的第一个子元素的集合;

$(“li:first-child”):没有空格,表示li是子元素,父元素是li的父元素,选择的是以li为第一个子元素的父元素(的第一个子元素)。有点拗口,总之不加空格,意思是li必须是所在父元素的第一个子元素。

例如:

<!DOCTYPE html>
<html>
<head>
<title>:first-child子元素过滤选择器</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>

<div>
<h3>h3是该div中第一个元素</h3>
<h3>1234</h3>
</div>
<div>
<h2>h2是该div中第一个元素</h3>
<h3>1234</h3>
<h3>1234</h3>
</div>
<script type="text/javascript">

// $("ol :first-child").css("background-color", "green");
$("h3:first-child").css("background-color", "green");
</script>
</body>
</html>


如下:第二个div的h2就没有变绿,因为他不是div的first-child



附上css的选择器:

1.id选择器( # myid)

2.类选择器(.myclassname)

3.标签选择器(div, h1, p)

4.相邻选择器(h1 + p)

5.子选择器(ul > li)

6.后代选择器(li a)

7.通配符选择器( * )

8.属性选择器(a[rel = "external"])

9.伪类选择器(a: hover, li:nth-child)


优先级为:

!important > id > class > tag

important 比 内联优先级高,但内联比 id 要高
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: