日期:2014-05-16  浏览次数:20280 次

jquery选择器加不加空格,晕了。
是这样的,我在使用

$("div:nth-child(1)");
发现没有反应,后来加了一个空格就可以了,
$("div :nth-child(1)");

不知道什么意思,然后,网上查询了一下,说是加空格表示后代,我用其他选择器测试基本可以说通,但是用这个测试,完全不是这样。

<div>
<div>11111111111</div>
<div>11111111111</div>
<div>11111111111</div>
</div>


<script language="javascript" type="text/javascript">
var $res=$("div:nth-child(1)");

$res.each(function(){
$(this).css({background:"red"});
});

</script>



不加空格:选中整个父div。
加空格:正常选中第一个div,但是按之前的说法,有了空格就是后代的意思,后代的第一个孩子,就不应该是第一个div了。

反正选择器的空格,特别是nth-child的空格,我已经晕了,,求分析。

------解决方案--------------------
:nth-child 指的是parentNode的第n个子元素。
所以$("div :nth-child(1)"); 匹配所有的div下面的第一个子元素。
$("div:nth-child(1)"); 匹配所有在parentNode中排第一的div

加点代码比较一下就知道了。

<div>
<div>aaa</div>
<div>bbb</div>
<div>ccc</div>
</div>
<div>
<div>ddd</div>
<div>eee</div>
<div>fff</div>
</div>
<button>div:nth-child(2)</button>
<button>div :nth-child(2)</button>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
<!--
$("button").click(function () {
var s= $(this).html();
$("div").css({background:""});
$(s).each(function(){
$(this).css({background:"red"});
});
});
//-->
</script>

------解决方案--------------------
try

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<title>无标题文档</title>
</head>

<body>
<div>
<div style="background-color:#ddd">11111111111</div>
<div style="background-color:#333">222222222222222222222222</div>
<div style="background-color:#999">5555555555555555555555555555</div>
</div>
        <script type="text/javascript">
  $(function() {
/*
$("div:nth-child(1)").each(function(){
$(this).css({background:"green"});
});
*/
$('div').children().first().css('background-color', 'green');
});
        </script>
</body>
</html>

------解决方案--------------------

<div id="o1"&