了解数组中的队列方法,DOM中节点的一些操作

队列的概念

栈是一种后进先出的结构,而队列是一种先进先出的结构。如银行排队,排在前面的人先办业务然后离开,后来的人站在最后。可以用队列的push()方法插入元素到队列的末尾,可以用shift()方法删除第一个元素。

模拟队列进行插入、删除

在html中生成新的节点
var str1 = document.createElement("li");

然后在把这个节点插入到ul中

ul.appendChild(str1);

在jquery中可以不用生成新的节点,直接用append()方法将它添加到上一个li后面

在第一个节点之前插入
insertBefore

定义

The insertBefore() method inserts a new child node before an existing child node.
insertBefore()

方法的作用是:在现有的子节点前插入一个新的子节点

用法

target.insertBefore(newChild,existingChild)

newChild作为target的子节点插入到existingChild节点之前

existingChild为可选项参数,当为null时其效果与appendChild一样

insertBefore例子

var oTest = document.getElementById("test");
var newNode = document.createElement("p");
newNode.innerHTML = "This is a test";
oTest.insertBefore(newNode,oTest.childNodes[0]);  
找到最后一个节点

最后一个节点就是li的长度减一,当然这只是其中一种方法。

删除节点
ul.removeChild(Rout);

完整代码

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
    <title></title>
	<style type="text/css">
        #ul li{
            list-style-type: none;
            display: inline-block;
             20px;
            height: 20px;
            padding: 5px;
            margin-right: 10px;
            text-align: center;
            background: red;
            color: white;
        }
    </style>
</head>
<body>
    <input type="text" id="text">
    <input type="button" id="botton1" value="左侧入">
    <input type="button" id="botton2" value="右侧入">
    <input type="button" id="botton3" value="左侧出">
    <input type="button" id="botton4" value="右侧出">
    <ul id="ul">
        <li>1</li>
    </ul>
<script type="text/javascript">
   window.onload = function() {
    var text_value;
    var Lenter = document.getElementsByTagName('input')[1];
    var Renter = document.getElementsByTagName('input')[2];
    var Lquit = document.getElementsByTagName('input')[3];
    var Rquit = document.getElementsByTagName('input')[4];
    var ul = document.getElementById('ul');
    //var str1 = '';
    Lenter.onclick = function() {
        text_value = document.getElementById('text').value;
        var str1 = document.createElement("li");
        str1.innerHTML = text_value;

        ul.insertBefore(str1,ul.childNodes[0]);
        //text_value = null;
    }
    Renter.onclick = function() {
        text_value = document.getElementById('text').value;
        var str1 = document.createElement("li");
        str1.innerHTML = text_value;

        ul.appendChild(str1);
    }
    Lquit.onclick = function() {
        var Lout = ul.getElementsByTagName('li')[0];
        console.log(Lout)
        ul.removeChild(Lout);
    }
    Rquit.onclick = function() {
        var length = ul.getElementsByTagName('li').length;
        var Rout = ul.getElementsByTagName('li')[(length-1)];
        ul.removeChild(Rout);
    }
   } 
</script>        
</body>
</html>
原文地址:https://www.cnblogs.com/huyuzhu/p/6591640.html