为了账号安全,请及时绑定邮箱和手机立即绑定

查找class="first-div"下的第一个a元素 为什么是$(".first-div a:first-child").css("color", "#CD00CD"); 为什么是$(".first-div:first-child").css("color", "#CD00CD");他的第一个子元素就是a元素啊

查找class="first-div"下的第一个a元素

为什么是$(".first-div a:first-child").css("color", "#CD00CD");

为什么是$(".first-div:first-child").css("color", "#CD00CD");他的第一个子元素就是a元素啊

正在回答

6 回答

我感觉前面都没答到点子上。

<div class="left first-div">
        <div class="div">
            <a>:first-child</a>
            <a>第二个元素</a>
            <a>:last-child</a>
        </div>
        <div class="div">
            <a>:first-child</a>
        </div>
        <div class="div">
            <a>:first-child</a>
            <a>第二个元素</a>
            <a>:last-child</a>
        </div>
    </div>

因为.first-div的第一个子元素是<div class="div">,$(".first-div:first-child")选中的是       

       <div class="div">
            <a>:first-child</a>
            <a>第二个元素</a>
            <a>:last-child</a>
        </div>

所以你会看到第一个盒子里的字全变成紫色了,如果删掉<div class="div">,变成如下

<div class="left first-div">
            <a>:first-child</a>
            <a>第二个元素</a>
            <a>:last-child</a>
        <div class="div">
            <a>:first-child</a>
        </div>
        <div class="div">
            <a>:first-child</a>
            <a>第二个元素</a>
            <a>:last-child</a>
        </div>
    </div>

那你写的代码就完全没有问题

0 回复 有任何疑惑可以回复我~
#1

随心183

不对吧,(:first-child)是选中所有父级元素下的第一个子元素,但是你写的$(".first-div:first-child"),里面的.first-div没有父级元素,因此它选不中.first-div下面的第一个子元素div
2019-06-25 回复 有任何疑惑可以回复我~

因为$(".first-div a:first child")的意思是选中的元素具备以下条件:1,必须是a元素;2,这个a元素还得是父级元素的第一个元素,否则选不中。

1 回复 有任何疑惑可以回复我~

因为这个题只写了a标签,如果还写了其他标签,就要按照具体要求选择出第一个a标签

0 回复 有任何疑惑可以回复我~
    $(":first-child")    
 这个选择器选择的是【在同一个父级元素】下的【所有子元素中】的【第一个元素】,所以前面的选择器应该选中的是【所有元素】这一块,而不是【父级元素】例如:
 <ul>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
 </ul>
  要用这个选择器选中第一个【li】,那么应该先选出【同一个父级元素】下的【所有元素】也就是【所有的li】,
  因此前面是
  $("ul li");
  然后再从【所有li】里面选出第一个【li】,也就是
  $("ul li:first-child");
 
 并不是CSS中的.firstChild这个属性,看清楚了哈


0 回复 有任何疑惑可以回复我~

$(".first-div:first-child").css("color", "#CD00CD")这个查找的是.first-div下面的所有的第一个元素,包括他的第一个子元素,也包括他的所有后代元素里面的所有第一个元素

0 回复 有任何疑惑可以回复我~

因为a是要被查找的元素,查找使用的方法是(":first-child")。

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

查找class="first-div"下的第一个a元素 为什么是$(".first-div a:first-child").css("color", "#CD00CD"); 为什么是$(".first-div:first-child").css("color", "#CD00CD");他的第一个子元素就是a元素啊

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信