jQuery - 使用类“.container”获取 div 中的所有 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5977699/
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-08-26 20:08:41  来源:igfitidea点击:

jQuery - get all divs inside a div with class ".container"

jquerydom

提问by kaiser

Scenario:

设想:

I got a menu containing links:

我有一个包含链接的菜单:

Main Menu Item
--------------
Sub: Show Grid > SubSub: <a>Show #first</a>
                         <a>Show #second</a>
                         <a>Show #third</a>

Now i need to find all divs with an css #IDwho are first level DOM elements inside the .containerdiv. These elements should get appended to "Sub: Show Grid" and add a class via a click on it.

现在我需要找到所有带有 css 的 div,#ID它们是div中的第一级 DOM 元素.container。这些元素应该附加到“Sub:Show Grid”并通过单击添加一个类。

<!-- The mark up -->
<div class="container">
    <div id="first">1st</div>
    <div id="second">2nd</div>
    <div id="third">3rd</div>
</div>

Question:

题:

  • How would i find the first level div with an (undefined/not known) #IDwith jQuery?
  • How can i interact with the result in php - will I get an array as result to build the SubSub menu out of it?
  • 我如何#ID使用 jQuery找到带有(未定义/未知)的第一级 div ?
  • 我如何与 php 中的结果交互 - 我会得到一个数组作为结果来构建 SubSub 菜单吗?

Thanks in advance!

提前致谢!



Edit #1

编辑 #1

To make it more clear what I'm trying to do - In pseudo code:

为了更清楚地说明我要做什么 - 在伪代码中:

$divs_received_from_jquery_fn = 'how do I get the divs (IDs?) as array(?) and interact with them in the following code?';
foreach ( $divs_received_from_jquery_fn as $div )
{
    add_menu_item( array( 
         'parent' => 'Sub: Show Grid'
        ,'name'   => 'Show #'.$div
        ,'href'   => ''
        ,'meta'   => array( 
                        'onclick' => 'jQuery(".container #".$div).toggleClass("showgrid");'
         ) 
    ) );
}

Edit #2

编辑 #2

The "real world" example. The output is an onclick event for an a-link. My problem is that i want to call the function foreachfor every div[id]below the .containerdiv and simply don't know how to interact properly with javascript & php.

“真实世界”的例子。输出是 a-link 的 onclick 事件。我的问题是我想为div下的foreach每个调用该函数,只是不知道如何与 javascript 和 php 正确交互。div[id].container

?>
<script type="text/javascript">
    jQuery(".container > div[id]").each(function(){
        var context = $(this);
        <?php 
        // SHOWGRID - parts
        // @since v0.3
        $wp_admin_bar->add_menu( // trigger the function via the global $wp_admin_bar var that calls the class
            array(
                 'parent'   => 'showgrid' // parent menu item
                ,'id'       => 'showgrid - ' + this.id // menu item ID
                ,'title'    => sprintf( // menu item label
                     __( '%1$s show grid parts %2$s%3$s', OXO_TEXTDOMAIN )
                    ,'<span style="background: none;">'
                    ,'<span class="showgridparts-on hide">&#x2714;</span>'
                    ,'<span class="showgridparts-off">&times;</span>' 
                 )
                ,'href'     => '' // stays empty to not trigger anything
                ,'meta'     => array( // HERE GOES THE ACTUAL jQuery FUNCTION
                    'onclick'   => 'jQuery("#" + this.id).toggleClass("showgrid"); jQuery(".showgridparts-on").toggleClass("hide"); jQuery(".showgridparts-off").toggleClass("hide"); return false;'
                 )
            ) 
        );
        ?>
    });
</script>
<?php

回答by Robert Koritnik

Known ID

已知 ID

$(".container > #first");

or

或者

$(".container").children("#first");

or since IDs should be unique within a single document:

或者因为 ID 在单个文档中应该是唯一的:

$("#first");

The last one is of course the fastest.

最后一个当然是最快的。

Unknown ID

未知身份

Since you're saying that you don't know their ID top couple of the upper selectors (where #firstis written), can be changed to:

既然你说你不知道他们的上级选择器的 ID 顶部(#first写在哪里),可以改为:

$(".container > div");
$(".container").children("div");

The last one (of the first three selectors) that only uses ID is of course not possible to be changed in this way.

仅使用 ID 的最后一个(前三个选择器中的)当然不可能以这种方式更改。

If you also need to filter out only those child DIVelements that define ID attribute you'd write selectors down this way:

如果您还需要仅过滤掉那些DIV定义 ID 属性的子元素,您可以这样写选择器:

$(".container > div[id]");
$(".container").children("div[id]");

Attach click handler

附加点击处理程序

Add the following code to attach click handler to any of your preferred selector:

添加以下代码以将点击处理程序附加到您喜欢的任何选择器:

// use selector of your choice and call 'click' on it
$(".container > div").click(function(){
    // if you need element's ID
    var divID = this.id;
    cache your element if you intend to use it multiple times
    var clickedDiv = $(this);
    // add CSS class to it
    clickedDiv.addClass("add-some-class");
    // do other stuff that needs to be done
});

CSS3 Selectors specification

CSS3 选择器规范

I would also like to point you to CSS3 selector specificationthat jQuery uses. It will help you lots in the future because there may be some selectors you're not aware of at all and could make your life much much easier.

我还想向您指出 jQuery 使用的CSS3 选择器规范。将来它会帮助你很多,因为可能有一些你根本不知道的选择器,可以让你的生活更轻松。

After your edited question

在您编辑的问题之后

I'm not completey sure that I know what you're after even though you've written some pseudo code... Anyway. Some parts can still be answered:

即使你写了一些伪代码,我也不完全确定我知道你在追求什么......无论如何。有些部分仍然可以回答:

$(".container > div[id]").each(function(){
    var context = $(this);
    // get menu parent element: Sub: Show Grid
    // maybe I'm not appending to the correct element here but you should know
    context.appendTo(context.parent().parent());
    context.text("Show #" + this.id);
    context.attr("href", "");
    context.click(function(evt){
        evt.preventDefault();
        $(this).toggleClass("showgrid");
    })
});

the last thee contextusages could be combined into a single chained one:

最后三个context用法可以组合成一个单一的链接:

context.text(...).attr(...).click(...);

Regarding DOM elements

关于 DOM 元素

You can always get the underlaying DOM element from the jQuery result set.

您始终可以从 jQuery 结果集中获取底层 DOM 元素。

$(...).get(0)
// or
$(...)[0]

will get you the first DOM element from the jQuery result set. jQuery result is always a set of elements even though there's none in them or only one.

将从 jQuery 结果集中获取第一个 DOM 元素。jQuery 结果始终是一组元素,即使它们中没有或只有一个。

But when I used .each()function and provided an anonymous function that will be called on each element in the set, thiskeyword actually refers to the DOM element.

但是当我使用.each()function 并提供一个匿名函数将在集合中的每个元素上调用时,this关键字实际上是指 DOM 元素。

$(...).each(function(){
    var DOMelement = this;
    var jQueryElement = $(this);
    ...
});

I hope this clears some things for your.

我希望这可以为您清除一些事情。

回答by James Wiseman

To get all divs under 'container', use the following:

要获取“容器”下的所有 div,请使用以下命令:

$(".container>div")  //or
$(".container").children("div");

You can stipulate a specific #idinstead of divto get a particular one.

您可以规定一个特定的#id而不是div获得一个特定的。

You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:

你说你想要一个带有“未定义”ID 的 div。如果我理解正确,以下将实现这一目标:

$(".container>div[id=]")

回答by user1161391

From http://api.jquery.com/jQuery/

来自http://api.jquery.com/jQuery/

Selector Context By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:

选择器上下文 默认情况下,选择器在 DOM 中从文档根开始执行它们的搜索。但是,可以通过使用 $() 函数的可选第二个参数为搜索提供替代上下文。例如,要在事件处理程序中进行搜索,可以像这样限制搜索:

$( "div.foo" ).click(function() { 
   $( "span", this ).addClass( "bar" );
});

When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.

当对 span 选择器的搜索仅限于 this 的上下文时,只有被单击元素内的 span 才会获得附加类。

So for your example I would suggest something like:

因此,对于您的示例,我建议如下:

$("div", ".container").each(function(){
     //do whatever
 });

回答by Digbyswift

To set the class when clicking on a div immediately within the .container element, you could use:

要在 .container 元素中立即单击 div 时设置类,您可以使用:

<script>
$('.container>div').click(function () {
        $(this).addClass('whatever')
    });
</script>