【问题标题】:What does last-child do exactly?最后一个孩子到底是做什么的?
【发布时间】:2015-03-06 07:22:55
【问题描述】:

假设我有以下 HTML:

<div class="motiv_input_container">
     <div class="hide_if_necessary">
          <span class="motiv_label">&nbsp;</span>
          <span class="motive_head_text">Menge inkl. Ersatz</span><span class="motive_head_text">Gesamtpreis zzgl. MwSt</span>
     </div>
     <div class="motiv_input_holder"></div>
     <div class="motiv_input_holder"></div>
     <div class="motiv_input_holder"></div>
     <div class="motiv_input_holder"></div>
     <div class="motiv_input_holder"></div>
     <div class="motiv_input_holder"></div> <--- I WANT TO SELECT THIS ONE
     <div class="hide_if_necessary">
         <span class="motiv_label">&nbsp;</span>
         <span class="motive_head_text">Gesamttotal zzgl. MwSt</span>
         <input type="text" class="motive_input_total_display">
      </div>
</div>

.motiv_input_holder 是通过 JS 加上下面这行的:

$(this).parent().parent().children(".motiv_input_container")
.children(".hide_if_necessary:first-child")
.after("<div class='motiv_input_holder'></div>");

因此,基本上,它们被添加在第一个和第二个 ".hide_if_necessary" 之间。现在,我希望能够删除最后一个".motiv_input_holder",但是,我遇到了一个小问题。我的第一次尝试是这个:

$(this).parent().parent().children(".motiv_input_container").children(".motiv_input_holder:last-child").remove();

但是,即使按照我的逻辑它们应该有,但这些都不起作用(顺便说一句,last-of-child 也不起作用)。现在,我用以下方法解决了它:

$(this).parent().parent().children(".motiv_input_container").children(".motiv_input_holder:nth-last-child(2)").remove();

我现在的问题是为什么?在这种情况下,last-child 不应该完全按照我的意愿去做吗?我错过了什么吗?

【问题讨论】:

  • 你的JS中this的上下文是什么?
  • last-child 必须是其父级的最后一个子级。Source.children(".motiv_input_holder:last") 应该可以工作。

标签: jquery css pseudo-class


【解决方案1】:

在 jQuery(和 CSS)中,:last-child 匹配其父元素的最后一个子元素。在你的情况下,它不是:在它之后还有一个孩子。在这种情况下,类是无关紧要的。

【讨论】:

    猜你喜欢
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 2016-08-19
    • 2012-02-09
    • 1970-01-01
    相关资源
    最近更新 更多