用JavaScript颠倒添加到DOM中的元素的顺序 [英] Reverse the order of elements added to DOM with JavaScript

查看:50
本文介绍了用JavaScript颠倒添加到DOM中的元素的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用JavaScript制作游戏,并且需要事件日志.如果我发动攻击,它会告诉我击中还是想念.这是我的代码:

I am making a game in JavaScript, and need an event log. If i attack, it tells me if i hit or i miss. Here is my code:

function eventlogshow (text){
    var para = document.createElement("p");
    var node = document.createTextNode(text);
    para.appendChild(node);

    var element = document.getElementById("eventlog");
    element.appendChild(para);
}

它在底部列出了最近的事件,在顶部列出了最早的事件.我该如何扭转呢?我希望它在顶部显示最近的事件.

It lists the most recent event on the bottom, with the oldest on top. How do i reverse that? I would like it to show the most recent event on the top.

推荐答案

改为添加子元素.由于没有 prependChild()函数,因此需要在第一个孩子之前插入":

Prepend the child element instead. Since there is no prependChild() function, you need to "insert it before the first child":

function eventlogshow (text){
    var para = document.createElement("p");
    var node = document.createTextNode(text);

    para.appendChild(node);

    var element = document.getElementById("eventlog");
    element.insertBefore(para, element.firstChild);
}

在这里提出了类似的问题:如何将DOM元素设置为第一个孩子?.

A similar question has been asked here: How to set DOM element as first child?.

详细了解 Node.firstChild Node.insertBefore()

Read more about Node.firstChild and Node.insertBefore()

这篇关于用JavaScript颠倒添加到DOM中的元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆