简体   繁体   English

选择嵌套元素

[英]Selecting nested elements

I have a page hierarchy like this: 我有这样的页面层次结构:

<div class="panel" attribute-id="1">
  <button class="delete">
  <div class="panel" attribute-id="2" association-id="20">
    <button class="delete">
  </div>
</div>
....

So I have a bunch of these panels with nested panels inside, and I'm trying to create on on click handler for the delete buttons of the top level panels only (so the ones immediately inside panels that do not have an association id). 因此,我有一堆这样的面板,其中有嵌套面板,并且我试图为顶级面板的删除按钮创建on click处理程序(因此,在面板内部的这些按钮没有关联ID)。 The only different between the parent and child panels is that the child ones have the extra attribute "association-id". 父面板和子面板之间的唯一区别是子面板具有额外的属性“ association-id”。

So I can select the top level panels only like so: 因此,我只能像这样选择顶级面板:

$('.panel[attribute-id]:not([association-id]')

But if I try to get the delete buttons from from these like: 但是,如果我尝试从这些按钮中获取删除按钮,例如:

$('.panel[attribute-id]:not([association-id] .delete')

Obviously I'm still going to get the child buttons. 显然,我仍然要获得子按钮。

I can't modify the html in anyway, how could I go about doing this? 无论如何我都无法修改html,我该怎么做呢?

$(':not(.panel[attribute-id][association-id]) > .delete')

seems to do the trick. 似乎可以解决问题。

jsfiddle 的jsfiddle

I've changed .panel-group to .panel to get it to work with the HTML provided. 我已经将.panel-group更改为.panel ,使其可以与提供的HTML一起使用。

Wrap them all in a div and assign that div a unique class. 将它们全部包装在一个div中,并为该div分配一个唯一的类。 Then you can use jquery selector ".panel-group > .panel" to get only direct children of top level. 然后,您可以使用jquery选择器“ .panel-group> .panel”仅获取顶级的直接子级。

<div class="panel-group">

 <div class="panel" attribute-id="1">
  <button class="delete">
  <div class="panel" attribute-id="2" association-id="20">
    <button class="delete">
  </div>
 </div>

 <div class="panel" attribute-id="11">
  <button class="delete">
  <div class="panel" attribute-id="12" association-id="120">
    <button class="delete">
  </div>
 </div>

</div>

您可以使用children方法:

$('.panel-group[attribute-id]').children('button').first()

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

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