简体   繁体   English

如何从div中删除最后一个元素?

[英]How to remove last element from div?

I have list of descriptions and after remove one of them, I'd like to remove last element from div, not refreshing site. 我有描述列表,删除其中一个后,我想删除div中的最后一个元素,而不是刷新网站。 I don't know javascript in fact, so I'd like to ask how should my destroy.js.erb looks like? 我其实不知道javascript,所以我想问一下我的destroy.js.erb应该怎么样? I can refresh whole class "descriptions" using 我可以使用刷新全班“描述”

$('.descriptions').load(location.href + " .descriptions");

but I'm interested, if there is way to remove only last element. 但我很感兴趣,如果有办法只删除最后一个元素。

  <div class="descriptions">
       <%= render @descriptions %> 
  </div>

 //_description.html.erb
 <div class="description-field">
        <%= @description.text %>
 </div>

Thank you for any help 感谢您的任何帮助

<div class="parent">
    <div class="child">
        Item 1
    </div>
    <div class="child">
        Item 2
    </div>
    <div class="child">
        Item 3
    </div>
</div>

The following line of jQuery would delete "Item 3." 以下jQuery行将删除“Item 3”。

$('.parent').children().last().remove();

Use css selector :last-child to remove it (found here ). 使用css selector :last-child删除它(在这里找到)。 Then use jQuery to remove last element. 然后使用jQuery删除最后一个元素。

$(".yourdiv :last-child").remove();

Here is jsFiddle example: 这是jsFiddle示例:

html: HTML:

<div>
    <p> Hello </p>
    <p> World </p>
    <p> last element </p>
</div>

JavaScript: JavaScript的:

$("div :last-child").remove();

Use this if you want to remove the last div: 如果要删除最后一个div,请使用此选项:

$("div:last").remove(); 

Use this if you want to remove the last sibling of some div with id "#mydiv" 如果你想删除id为“#mydiv”的某个div的最后一个兄弟,请使用此选项

$('#mydiv:last-child')
<div id="parent">
    <div id="child">
        Item 1
    </div>
    <div id="child">
        Item 2
    </div>
    <div id="child">
        Item 3
    </div>
</div>

The following is a JQuery code that removes the last child item 3 以下是删除最后一个子项3的JQuery代码

$("#child").remove();

or you can also use 或者你也可以使用

$("#child").css({"display": "none"});

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

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