简体   繁体   English

jquery选择多个 <p> 在 <div>

[英]jquery select multiple <p> in <div>

HTML: HTML:

<div id='example'>
  <p> First paragraph</p>
  <p> Second paragraph</p>
  <p> Third paragraph</p>
</div>

Javascript with JQuery: var paragraphs = $('div#examples p'); 使用JQuery的Javascript: var paragraphs = $('div#examples p');

This returns an array of HTMLParagraphElement objects. 这将返回HTMLParagraphElement对象的数组。 However, I wish to return Jquery objects. 但是,我希望返回Jquery对象。 (So that I can use eg: (所以我可以使用例如:

for(i=0;i<paragraphs.length;i++)
{
   paragraph[i].hide();
}

Is there a way I can easily do this? 有没有办法轻松做到这一点? Thanks. 谢谢。

example: 例:

$('#examples p').hide();

div is not necessary div不是必需的

You can still use the the selector query you use. 您仍然可以使用您使用的选择器查询。 ie: 即:

var paragraphs = $('div#examples p');
 paragraphs.hide();

or 要么

 $('div#examples p').hide();

This the the most performant way to query the dom for present issue: 这是查询当前问题的dom最高效的方法:

$('#examples).find('p').hide();

It's a few more keystrokes, but the selection happens so much faster than the examples given here by others. 这是一些按键,但选择的速度比其他人给出的例子要快得多。 The reason being is that it traverses all divs first, then finds those that may have the given id, then traverses to find their matching p tags. 原因是它首先遍历所有div,然后找到那些可能具有给定id的那些div,然后遍历以找到它们匹配的p标签。

In my solution it finds just #examples and then traverses down to its p tag. 在我的解决方案中,它只找到#examples ,然后遍历到它的p标签。

Thanks everybody for input. 谢谢大家的投入。 Iteration of the div p array was necessary (sorry if that wasn't clear), so doing $('div#example p').hide(); 迭代div p数组是必要的(如果不清楚则很抱歉),所以做$('div#example p').hide(); was not a proper solution. 不是一个合适的解决方案。 I ended up doing the following: 我最后做了以下事情:

var arr = $('div#example p');

for(i=0;i<arr.length;i++)
{
  $(arr[i]).hide();
}

Hope this is useful for people in the future:) 希望这对未来的人有用:)

尝试这个...

$('div#examples p').hide();

From the looks of your question the answer would be, as stated by others: 从你问题的外观来看,答案就是如其他人所说:

$('div#examples p').hide();

But for the case that you have to iterate through each object that is returned from a jQuery query you should use this syntax: 但是对于必须遍历从jQuery查询返回的每个对象的情况,您应该使用以下语法:

$('div#examples p').each(function(){
    $(this).hide();
});

But remember, if it's as simple as hide, then just use the first example. 但请记住,如果它像hide一样简单,那么只需使用第一个例子。 The second example is when the applied function is specific to each object. 第二个示例是应用函数特定于每个对象的时间。 The next example is doubling the heights of all returned objects, which could not be done in the same way that the first example is: 下一个示例是将所有返回对象的高度加倍,这与第一个示例的方式不同:

$('div#examples p').each(function(){
    var h = $(this).height();
    $(this).height(h * 2);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM