如何使用jQuery将元素始终添加为最后一个元素?
无论如何,我都希望将某个div作为列表中的最后一个元素添加.有什么方法可以明确地指定它?
I want a certain div to be added as the last element in a list no matter what. Is there any way in which I can explicitly specify this?
获取列表的父项,并将新项添加到该父项中作为最后一个子项.
Get the parent of the list and add the new item to that parent as the last child.
使用普通javascript:
Using plain javascript:
parent.appendChild(newElement);
Mozilla文档: https://developer.mozilla.org/En/DOM/Node.appendChild
Mozilla documentation: https://developer.mozilla.org/En/DOM/Node.appendChild
如果要添加其他项目,但仍将此项保留为最后一项,则必须在此最后一项之前添加新项目,或删除该项目,追加新项目,然后再次将其追加到结束.
If you want to add other items and still have this item be the last item, then you will have to add the new items before this last item or remove this item, append your new item, then append this one back again at the end.
一旦您已经拥有列表中的最后一个元素,那么如果您想在该最后一个元素之前添加一个新元素,则可以这样操作:
Once you already have the last element in the list, if you then want to add a new element right before that last element, you can do it like this:
parent.insertBefore(newElement, parent.lastChild);