動態購物列表 瞭解一下(前端)
阿新 • • 發佈:2019-02-06
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8"/>
<style>
body{
background: bisque;
}
</style>
</head>
<body >
<h1 style="text-align: center;" >My shopping list</h1>
<div style="border: 1px solid black;width: 400px;margin: auto;">
Enter a new item:<input /><button id="addItem">Add item</button>
<ul style="width: 200px;margin: auto;">
</ul>
</div>
<script>
var ctn=0;
var addItem =document.getElementById('addItem');
var input = document.querySelector('input');
addItem.onclick =function(){
var listItem = document.createElement('li');
listItem.style.margin=0+'px';
var span = document.createElement('span' );
var button = document.createElement('button');
button.innerHTML='delete';
button.setAttribute('id','id'+ctn);
span.innerHTML=input.value+ctn++;
listItem.appendChild(span);
listItem.appendChild(button);
var list = document.querySelector('ul');
list.appendChild(listItem);
button.onclick= function(){
listItem.parentNode.removeChild(listItem)
}
}
</script>
</body>
</html>