<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload = function() {
var oBtn = document.getElementById('btn1');
var oTxt = document.getElementById('txt1');
var oUl = document.getElementById('ul1');
var aA = [];
oBtn.onclick = function() {
var oLi = document.createElement('li');
var aLi = document.getElementsByTagName('li');
// add <a> to li
oLi.innerHTML = oTxt.value + ' <a href="javascript:;">delete</a>';
if (aLi.length > 0) {
oUl.insertBefore(oLi, aLi[0]);
} else {
oUl.appendChild(oLi);
}
// everytime add an li, add <a> which is in <li> to aA
aA.push(oLi.children[0]);
};
for (var i = 0; i < aA.length; i++) {
aA[i].onclick = function() {
oUl.removeChild(this.parentNode);
}
}
}
</script>
</head>
<body>
<input id='txt1' type="text" />
<!-- Add an li element -->
<input id="btn1" type="button" value="Add li" />
<ul id="ul1">
</ul>
</body>
</html>
Hi everyone, I'm a javascript beginner, and I have a trouble in click event, following is my problem:
When I click oBtn.onclick
, it create an li
element to ul
, then innerHTML
of li
contains tag "a" and be pushed to an array named aA.
However, in aA[i].onclick
, it doesn't work, so what is the problem in my code?