[ jquery 选择器 :nth-last-child ] 选取属于其父元素的不限类型的第 n 个子元素的所有元素,从最后一个子元素开始计数

选取属于其父元素的不限类型的第 n 个子元素的所有元素,从最后一个子元素开始计数:

实例:

<!DOCTYPE html>
<html lang='zh-cn'>
<head>
<title>Insert you title</title>
<meta http-equiv='description' content='this is my page'>
<meta http-equiv='keywords' content='keyword1,keyword2,keyword3'>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<script type='text/javascript' src='./js/jquery-1.12.1.min.js'></script>
<style type='text/css' >
    *{margin:0;padding:0;}
    html{font:400 15px/1.2em 'Courier New';color:#666;}
    div > *{margin:10px 0;cursor:pointer;}
    #demo{width:750px;margin:75px auto;}
    button{padding:5px 15px;border:0;outline:none;margin-top:-5px;border-radius:2px;font:400 12px/1.2em 'Courier New';}
    .active{background-color:yellow;transition: .3s;}
    .hover{background-color:red;transition: .3s}
    p{text-indent:8px;}
</style>
<script type='text/javascript'>
        /**
            概述
                选择所有他们父元素的第n个子元素。计数从最后一个元素开始到第一个。
                因为jQuery的实现:nth-child(n)是严格来自CSS规范,所以n值是“1索引”,也就是说,从1开始计数。对于所有其他选择器表达式,
                jQuery遵循JavaScript的“0索引”的计数。
            实例:                          
                <ul>
           <li></li>
           <li></li>
         </ul>

          $('li:nth-child(1)')选择第一个<li>,$('li:eq(1)')选择第二个<li>
                里面接受参数 even odd表示奇偶数,同时也接收表达式算法
        */
    $(function(){
        //1. $('p:nth-last-child(2)').addClass('active');
           
        //2. $('p:nth-last-child(3)').addClass('hover');
           
        // 使用下面方法 : 可以使用这种方法来进行小范围面积的元素选取 ,如果不指定范围就是在所有的父元素中选择子元素
           
          $('p:nth-last-child(3)','div:nth-child(2)').addClass('hover');        
    });
</script>
</head>
<body>
    <div id='demo'>
        <p class='test'>The first paragraph in div.</p>     <!-- 2. red -->
        <div style='border:1px solid #3695BC'>
            <p>The first paragraph in div.</p>
            <p>The last paragraph in the div.1</p>
            <p>The last paragraph in the div.1</p>
            <p>The last paragraph in the div.1</p>
            <p>The last paragraph in the div.1</p>      <!-- 1. yellow-->   <!-- 2. red -->  
            <p>The last paragraph in the div.11</p>     
        </div>
        <div style='border:1px solid #3695BC'>
            <p>The first paragraph in another div.2</p>
            <p>The last paragraph in another div.2</p>
            <p>The last paragraph in another div.2</p>
            <p>The last paragraph in another div.2</p>      <!-- 1. yellow -->   <!-- 2. red -->  
            <p>The last paragraph in another div.22</p>
        </div>
    </div>
</body>
</html>
posted @ 2016-06-24 16:01  窗棂  Views(500)  Comments(0Edit  收藏  举报