jQuery 子元素选择

对于如下代码片段  如何对河meishi这个div的子DIV呢?

<div id="vertical-Menu-meishi" class="J-nav-item">
    <div id="yui_3_12_0_1_1387858313977_228"  >
        <div id="yui_3_12_0_1_1387858313977_227" ></div>
        <div id="yui_3_12_0_1_1387858313977_424"  ></div>
    </div>
</div>

参考http://api.jquery.com/first-child-selector/

http://api.jquery.com/nth-child-selector/

不过上述都没有说明  :nth-child(2) 可以用在children()的括号中... 

不过想想  :nth-child(2)本身是选择器表达式   children('selector')  括号中也是选择器表达式

所以它就干脆没说

stackoverflow上又两个问答也很好的

http://stackoverflow.com/questions/4727263/jquery-get-second-child

http://stackoverflow.com/questions/5440792/getting-the-2nd-child-element

(后一篇中第一个回答的方案3 似乎行不通)

        $("#yui_3_12_0_1_1387858313977_424").css('display', 'block');//ok
        //表示的是获取#vertical-Menu-meishi下得第一个DIV元素         
        alert($("#vertical-Menu-meishi div:first-child").attr("id"));//ok
        alert( ($("#vertical-Menu-meishi").children(':first-child')).attr("id"));//ok
        //获取第一个子元素的第一个子元素
        alert( $("#vertical-Menu-meishi").children(':first-child').children(':first-child').attr('id') );//ok
        //获取第一个子元素的第二个子元素
        alert( $("#vertical-Menu-meishi").children(':first-child').children(':nth-child(2)').attr('id') );//ok

        //或者使用下面的办法  感觉更加容易理解
        //获取第一个子元素
        alert( $("#vertical-Menu-meishi").children('div').eq(0).attr('id') );//ok
        获取第一个子元素下的第二个子元素
        alert(  $("#vertical-Menu-meishi").children('div').eq(0).children('div').eq(1).attr('id')  );//ok

显然后面几种方式更好  第一个的话  第一种形式 对于$(this)这样的表达式就无能为力啦

原文地址:https://www.cnblogs.com/cart55free99/p/3511419.html