If there are about 10 buttons and the buttons are numbered from 1 to 10, if button 1 is clicked, object 1 is created. If button 2 is clicked, object 2 is created and the remaining objects 1, 3 and 4 are deleted. I want to become In the present case, it is implemented by hard coding, but I want to keep this code neat and short. Help.
this is my code
document.getElementById("leg_type2").addEventListener("click", function() { Group1.children[1].visible = !Group1.children[1].visible; Group1.children[0].visible = false; Group1.children[2].visible = false; Group1.children[0].scale.set(0, 0, 0) Group1.children[1].scale.set(1, 1, 1) Group1.children[2].scale.set(0, 0, 0) }); document.getElementById("leg_type3").addEventListener("click", function() { Group1.children[2].visible = !Group1.children[2].visible; Group1.children[1].visible = false; Group1.children[0].visible = false; Group1.children[0].scale.set(0, 0, 0) Group1.children[1].scale.set(0, 0, 0) Group1.children[2].scale.set(1, 1, 1) });
Advertisement
Answer
You can create a function that does this work for you:
document.getElementById("leg_type2") .addEventListener("click", function () { toggle(2); }); document.getElementById("leg_type3") .addEventListener("click", function () { toggle(3); }); function toggle(index) { const { children } = Group1; for (let i = 0; i < children.length; i++) { if (i !== index) { children[i].visible = false; children[i].scale.set(0,0,0); } } children[index].visible = true; children[index].scale.set(1, 1, 1); }