</head>
<body>
<input type="text" id='input-num'>
<button type="button" name="button" id="leftin">左侧入</button>
<button type="button" name="button" id="rightin">右侧入</button>
<div id="position">
<span id="none">a</span>
</div>
<script type="text/javascript">
var position = document.getElementById("position");
var order = document.getElementById("none");
var input = document.getElementById("input-num");
var input_num = input.value;
var leftin = document.getElementById("leftin");
var rightin = document.getElementById("rightin")
rightin.onclick = function rightwrap(){
var input_num = input.value;
if (input_num%1 === 0) {
position.innerHTML += "<span>" + input_num + "</span>";
}
}
leftin.onclick = function leftwrap() {
var input_num = input.value;
if (input_num%1 === 0){
var left = document.createElement("span");
left.textContent = input_num;
var parent = order.parentNode;
parent.insertBefore(left, position.firstChild);
}
}
</script>
</body>
两段函数都可以执行,但问题是当我在 Input 中输入数字后点击左侧入按钮,再点击右侧入按钮,再点击左侧入时,就出现以下的提示:
Uncaught TypeError: Cannot read property
'insertBefore' of null at HTMLButtonElement.leftwrap
执行了上面那条语句后#position元素下的子元素#none与order变量指向的元素就不是同一个元素了。
因为此时的order指向的元素只是存在于内存中,所以它的parentNode是null,执行下面这条语句的时候就会失败。