我正在尝试获取并显示输入。当我输入数字(例如4)时,我的文档将循环显示数字,其数量取决于输入的数字。我尝试以一种方式进行操作,如果我想再次输入一个数字,则会创建一个新列表,而旧列表将被删除。负责此工作的代码由行分隔。
<div id="get-numbers">
<label for="input-one">Enter the number</label><br>
<input type="text" id="input-one">
<div id="container-numbers"></div>
</div>
<script>
document.querySelector('#input-one').addEventListener('keypress', function(e){
var inputOneValue = document.getElementById('input-one').value;
var key = e.which || e.keyCode;
if (key == 13){
if (inputOneValue>=0){
document.getElementById('input-one').value = ' ';
//----------------------------------------------
var getNumbers = document.getElementById('container-number');
var child = getNumbers.children;
if (child != 0){
var divNumber = document.getElementsByClassName('div-number');
getNumbers.removeChild;
}
//----------------------------------------------
else{
for (var i=0; i<inputOneValue; i++){
var numberLi = document.createElement('DIV');
numberLi.className = 'div-number';
var numberText = document.createTextNode(i);
numberLi.appendChild(numberText);
getNumbers.appendChild(numberLi);
}
}
}
else document.getElementById('input-one').value = ' ';
}
});
</script>
答案 0 :(得分:1)
javascript HTML DOM方法romoveChild()
,删除父元素的子元素。
要从父级移除子级,我们需要将子级引用传递给removeChild()
方法。
更新的脚本:
document.querySelector('#input-one').addEventListener('keypress', function(e){
var inputOneValue = parseInt(document.getElementById('input-one').value);
var key = e.which || e.keyCode;
if (key == 13){
if (inputOneValue >= 0){
document.getElementById('input-one').value = '';
//----------------------------------------------
var getNumbers = document.getElementById('container-number');
var childs = getNumbers.childNodes;
if (childs.length > 0){
for (var i = 0; i < childs.length; i++) {
getNumbers.removeChild(childs[i]);
}
// Alternative but slower
// getNumbers.innerHTML = '';
}
//----------------------------------------------
else{
for (var i=0; i<inputOneValue; i++){
var numberLi = document.createElement('DIV');
numberLi.className = 'div-number';
var numberText = document.createTextNode(i);
numberLi.appendChild(numberText);
getNumbers.appendChild(numberLi);
}
}
}
else {
document.getElementById('input-one').value = '';
}
}
});