在控制台上,它应该打印以数组形式创建的特定div的div id,并且每次创建div时,其值应存储在数组中,每当删除div时,应从数组中删除相应div的值。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click the button to make a Division element.</p>
<button id="button" onclick="myFunctionTry()">Add</button>
<div id="myDIV">
</div>
<script>
var counter=1;
function myFunctionTry()
{
var x = document.createElement("DIV");
x.id="div"
var z= document.createElement("button");
z.id="btn";
x.setAttribute("style", "border :1px solid;height: 250px; width: 250px; top: 741px; left: 491px; padding:10px; margin: 50px;");
z.setAttribute("style", "background: #000 url(/home/subodh/Desktop/Widget/icon_incorrect.svg) no-repeat 0px 0px; height: 30px; width:40px; top: 6px; left: 4px; float: right; margin: 0px; padding:0px; clear: both; float:right;");
x.appendChild(z);
document.body.appendChild(x).appendChild(z);
var divNumber = counter;
counter++;
var arr=[];
arr.push(divNumber);
console.log(arr);
z.onclick = function remove(btn)
{
x.parentElement.removeChild(x);
var arr1=arr;
console.log(arr1);
}
}
</script>
</body>
</html>
如何获得输出:[1] [1,2] [1,2,3] .......运行上述代码。 M getn输出为[1] [2] [3] .......如何使用javascript完成此操作。
答案 0 :(得分:0)
您需要在函数外部定义数组变量。请参阅以下代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click the button to make a Division element.</p>
<button id="button" onclick="myFunctionTry()">Add</button>
<div id="myDIV">
</div>
<script>
var counter = 1;
var arr = [];
function myFunctionTry() {
var x = document.createElement("DIV");
x.id = "div"
var z = document.createElement("button");
z.id = "btn";
x.setAttribute("style", "border :1px solid;height: 250px; width: 250px; top: 741px; left: 491px; padding:10px; margin: 50px;");
z.setAttribute("style", "background: #000 url(/home/subodh/Desktop/Widget/icon_incorrect.svg) no-repeat 0px 0px; height: 30px; width:40px; top: 6px; left: 4px; float: right; margin: 0px; padding:0px; clear: both; float:right;");
x.appendChild(z);
document.body.appendChild(x).appendChild(z);
var divNumber = counter;
counter++;
arr.push(divNumber);
console.log(arr);
z.onclick = function remove(btn) {
x.parentElement.removeChild(x);
var arr1 = arr;
console.log(arr1);
}
}
</script>
</body>
</html>
&#13;