D
Deleted member 2829
Guest
On my web page I have a table or list that is populated dynamically. The rows/items have an
onclick()
handler so that when I click on one it gets highlighted (and the one previously highlighted gets un-highlighted). This works perfectly fine, UNTIL I temporarily change the document body html and replace it back to its original value (a trick I use to print a specific div on the page). Obviously I restore the event handlers, as they have been obliterated. The highlighting still works, except now the one that was highlighted remains highlighted when I click another one. Phew, some description... Maybe someone can try out my code which I pared down to the absolute minimum. After loading, click on a drink to highlight it. Then press the "fubar" button which does the THING. Now click another item and bingo, two items are highlighted. I really have no clue why this should be. Any ideas would be much appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
<style>
.selected { color : red; font-weight: bold }
.normal { color : black; font-weight: normal }
</style>
<script>
var selected;
function fubar()
{
document.body.innerHTML = document.body.innerHTML;
addEventHandlers();
}
function select(item)
{
if ( selected != null )
selected.className = "normal";
selected = item;
selected.className = "selected";
}
function addEventHandlers()
{
for (let li of document.getElementsByTagName('li'))
li.addEventListener('click', function() { select(this); });
}
function init()
{
document.getElementById("ul").appendChild(document.createElement("li")).innerHTML = "Coffee";
document.getElementById("ul").appendChild(document.createElement("li")).innerHTML = "Tea";
document.getElementById("ul").appendChild(document.createElement("li")).innerHTML = "Milk";
addEventHandlers();
select(ul.firstChild);
}
</script>
</head>
<body onload="init()">
<ul id="ul"></ul>
<button onclick="fubar()">fubar</button>
</body>
</html>