用Jquery选择第一个孩子的孩子

elb*_*ron 2 jquery select children find

我有一个像这样的html结构:

<div class="one">
  <div id="two">
    <h2>Any</h2>
    <h4>Any</h4>
  </div>
  <div id="three">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我必须选择第一个和第一个子元素:#two,h2,h4,而不知道第一个元素的id名称.我怎么能这样做?

我可以选择第一个元素,但是如果我添加内容().find()到div:首先我不能选择它的子元素:

$(document).ready(function() {
    $(".one").mouseover(function () {  
        $(this).children('div:first').contents().find('h2,h4').stop(true, true).fadeIn('fast');
     });

    $(".one").mouseout(function () { 
        $(this).children('div:first').contents().find('h2,h4').stop(true, true).fadeOut('fast');
    });
});
Run Code Online (Sandbox Code Playgroud)

最终和工作(没有闪烁!)代码是:

$(".one").hover(function () {  
$(this).children('div:first').stop(true, true).fadeIn('fast');
}, function() {;
$(this).children('div:first').stop(true, true).fadeOut('fast');
});
Run Code Online (Sandbox Code Playgroud)

我想在来这里问问题之前我必须给自己更多时间思考.无论如何,我学习了.andSelf()和一些Jquery语法.再次感谢.

ira*_*ama 6

你不需要同时使用find()contents()- 试试这个:

$(document).ready(function() {
    $(".one").mouseover(function () {  
        $(this).children('div:first').children('h2,h4').stop(true, true).fadeIn('fast');
     });

    $(".one").mouseout(function () { 
        $(this).children('div:first').children('h2,h4').stop(true, true).fadeOut('fast');
    });
});
Run Code Online (Sandbox Code Playgroud)

如果您还需要在节点集中保留"first"元素,请.andSelf()在第二个元素之后使用.children()(根据@Felix的答案).