Jump to content

nested functions and e.target


Chogori
 Share

Recommended Posts

I am trying to write a script, which:

• after the click on any <td> cell makes <div id="pole"> visible

• after the click on one of the <li> from <div id="pole> take the content of this li and insert it to <td> cell, which onclick makes <div> visible AND change <div> visibility back to "hidden"

Everything works almost fine. Almost...

For example:

1) I click on some <td> cell and then choose <li> "strength" - that´s ok, "strength" is written to that cell

2) After that I click on another cell and choose <li> "endurance" - "endurance" is written to that cell, BUT the content of the first cell is changed to "endurance" too

 

Can somebody fix it? And explain me where is the mistake? Whole code is here: https://jsfiddle.net/4odhrgLL/2/ Thanks a lot and sorry for my english...

var ParentTable = document.getElementById("mytable");var childTD = ParentTable.getElementsByTagName("td");var pole = document.getElementById("pole");var rest = document.getElementById("rest");var treningType = pole.getElementsByTagName("li");for(i=0;i<childTD.length;i++) {      childTD[i].addEventListener("click", clickTD);}                              function clickTD(e) {    var currentTD = e.target;    pole.style.visibility = "visible";    for(j=0;j<treningType.length;j++) {      treningType[j].addEventListener("click", insertToTD);	}    function insertToTD(e) {        var currentTraining = e.target;    	currentTD.innerHTML = currentTraining.innerHTML;        pole.style.visibility = "hidden";    } }
Link to comment
Share on other sites

You're assigning the li click handler inside the td click handler. So, every time you click on a td you're assigning another handler for the li click. If you click on 5 tds then it's going to run li click handlers 5 times the next time you click.

  • Like 1
Link to comment
Share on other sites

That's not a bad way to do it. Another way would be to use a data attribute on each LI to store the ID or something for the TD that was clicked on, but that may get a little clunky. Another way would be to give the TD a class, and then inside the LI handler you look up the element with that class, write to it, and then remove the class.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...