Javascript refactoring

Is there a better way to write this function? I have inherited javascript code, and I would like to make it more concise if possible. In addition, I will probably add many more "theme" elements and do not want to copy and paste over and over again.

function imageClick() { var theme1 = document.getElementById("li-theme1"); var theme2 = document.getElementById("li-theme2"); var theme3 = document.getElementById("li-theme3"); var imgtheme1 = theme1.getElementsByTagName("img"); var imgtheme2 = theme2.getElementsByTagName("img"); var imgtheme3 = theme3.getElementsByTagName("img"); var inputtheme1 = document.getElementById("radiotheme1"); var inputtheme2 = document.getElementById("radiotheme2"); var inputtheme3 = document.getElementById("radiotheme3"); imgtheme1[0].onclick = function() { inputtheme1.checked = true; highlightChoice("li-theme1"); } imgtheme2[0].onclick = function() { inputtheme2.checked = true; highlightChoice("li-theme2"); } imgtheme3[0].onclick = function() { inputtheme3.checked = true; highlightChoice("li-theme3"); } } 
+4
source share
2 answers
 function imageClick() { for (var i=1; i<4; i++) { var theme = document.getElementById("li-theme"+i); var imgtheme = theme.getElementsByTagName("img"); imgtheme[0].onclick = (function (current) { return function() { document.getElementById("inputtheme"+current) = true; highlightChoice("li-theme"+current); } })(i); } } 

If you want to add more iterations at a later date, simply increase 4 in i<4 to the number of iterations you want to perform + 1.

+4
source

I "hardcoded" the imageClick () function for the ones you specified, but you can change it as "for (var i = 1; i <4; i ++) {imageClickItem (i);}" if you want.

 function imageClick() { imageClickItem(1); imageClickItem(2); imageClickItem(3); } function imageClickItem(itemNumber) { var theme = document.getElementById("li-theme" + itemNumber); var imgtheme = theme.getElementsByTagName("img"); var inputtheme = document.getElementById("radiotheme" + itemNumber); imgtheme[0].onclick = function() { inputtheme.checked = true; highlightChoice(theme.id); } } 
+4
source

Source: https://habr.com/ru/post/1301844/


All Articles