假设我有以下HTML:
<div class="motiv_input_container">
<div class="hide_if_necessary">
<span class="motiv_label"> </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"> </span>
<span class="motive_head_text">Gesamttotal zzgl. MwSt</span>
<input type="text" class="motive_input_total_display">
</div>
</div>
通过JS添加.motiv_input_holder
,其中包含以下行:
$(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
不应该完全按照我的意愿行事吗?我错过了什么吗?
答案 0 :(得分:0)
在jQuery(以及CSS)中,:last-child
匹配作为其父级的最后一个子元素的任何元素。在你的情况下,它不是:在它之后还有一个孩子。在这种情况下,类是无关紧要的。