javascript jQuery:找到前两个孩子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10659283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:35:36  来源:igfitidea点击:

jQuery: Find first two children

javascriptjqueryhtmlcss

提问by colindunn

Using jQuery, what would be the most efficient way to find the first two children of a parent element, if one is an h1and the other is a p. My code isn't working right now, and I would like to accomplish this using best practices.

使用 jQuery,如果一个是 anh1而另一个是 a ,那么查找父元素的前两个子元素的最有效方法是什么p?我的代码现在无法正常工作,我想使用最佳实践来实现这一点。

CSS

CSS

div > *{
    display: none;
}

HTML

HTML

<div>
    <h1>Heading</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</div>

<div>
    <h1>Heading</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</div>

Javascript

Javascript

$('div h1').show();    
$('div p:first-child').show();

EditI'm actually working with multiple DIVs. I didn't think it would make a difference, but it looks like I was wrong.

编辑我实际上正在使用多个 DIV。我不认为这会有所作为,但看起来我错了。

回答by Selvakumar Arumugam

Try,

尝试,

$('div').children().slice(0,2).show();

Incase if you have more that 1 div, then try like below,

如果您有超过 1 个 div,请尝试如下操作,

$('div').each (function () {
    $(this).children().slice(0,2).show();
});

回答by Fabrizio Calderan

an alternative way to slice()method:

另一种slice()方法:

$('div').children(':lt(2)').show()

(but I recommend the slice too, especially for large collections)

(但我也推荐切片,特别是对于大集合)

回答by aquinas

回答by seyed

$('div p:first-child,div p:nth-child(2)').show();

回答by Madcat

$('div').children().slice(0, 2).show();

回答by Prasenjit Kumar Nag

You can user the less thanselector like following

您可以使用小于选择器,如下所示

$('div > *:lt(2)').show();

Working fiddle

工作小提琴

回答by aziz punjani

A descriptive selector would be

描述性选择器将是

$('div').find('h1:first, p:first').show(); 

This makes it clear what your intent is and what elements you're selecting.

这可以清楚地表明您的意图是什么以及您正在选择哪些元素。

回答by Elliot Bonneville

I think you'll want the eq()function, like this:

我想你会想要这样的eq()功能:

$("div").children().eq(0); // first child
$("div").children().eq(1); // second child

回答by levik

Not sure why you need to use jQuery for this.

不知道为什么你需要为此使用 jQuery。

var firstChild = div.firstChild;
firstChild.style.display = 'initial';
firstChild.nextSibling.style.display = 'initial';