下面的代码工作正常,除了计数器。当我将一个项目添加到列表中时,计数器是准确的,但是当我从列表中删除一个项目时,它不会从计数器中减去一个。有任何想法吗?
HTML
<nav>
<div id ="counter">1</div>
<ul id="list">
<li class="test" id="liOne"><a href="#">test</a></li>
</ul>
<p id="contOne"></p>
<a id="button" class="button btn" href="#">Add</a><br>
<a id="button" class="button removeBtn" href="#">Remove</a>
</nav>
JavaScript
var elList, addLink, newEl, netText, counter, listItems, removeLink, removeEl;
elList = document.getElementById('list');
addLink = document.querySelector('.btn');
counter = document.getElementById('counter');
removeLink = document.querySelector('.removeBtn');
function addItem(e) {
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false; //IE fallback code
}
newEl = document.createElement('li');
newText = document.createTextNode('New List Item');
newAnchor = document.createElement('a');
newAnchor.setAttribute('href', '#');
newAnchor.appendChild(newText);
newEl.appendChild(newAnchor);
elList.appendChild(newEl);
}
function removeItem(e) {
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false; //IE fallback code
}
var removeEl = document.querySelector('li');
var containEl = removeEl.parentNode;
containEl.removeChild(removeEl);
}
function updateCount() { // Declare function
listItems = elList.getElementsByTagName('li').length; // Get total of <li>s
counter.innerHTML = listItems; // Update counter
}
removeLink.addEventListener('click', removeItem, false);
addLink.addEventListener('click', addItem, false);
elList.addEventListener('DOMNodeInserted', updateCount, false); // DOM updated. fires when a node is inserted into dom tree
elList.addEventListener('DOMNodeRemoved', updateCount, false);