简体   繁体   中英

Getting elements from one function in another one

This functions work fine when they work alone, but when I try toggle between them, I got same elements in both arrays. Some are multiply by numbers of clicks others not.

 var playerBtn1 = []; var playerBtn2 = []; var btn = document.getElementsByTagName("button"); playerA(); function playerA() { for(let i = 0; i <btn.length; i++) { btn[i].addEventListener("click", () => { playerBtn1.push(btn[i]); playerB(); }); } return playerBtn1; } function playerB() { for(let k = 0; k <btn.length; k++) { btn[k].addEventListener("click", () => { playerBtn2.push(btn[k]); playerA(); }); } return playerBtn2; }

Edit. I've solved my problem, I just got rid of my functions and one of Event Listener. Put everything together and it works. Below I post my improved cod.

 var playerBtn1 = []; var playerBtn2 = []; var click = 0; var btn = document.getElementsByTagName("button"); for(let i = 0; i <btn.length; i++) { btn[i].addEventListener("click", () => { if(click % 2 == 0) { btn[i].innerHTML = '<i class="fas fa-times fa-5x"></i>'; btn[i].disabled = "true"; playerBtn1.push(btn[i].id); } else { btn[i].innerHTML = '<i class="far fa-circle fa-4x"></i>'; btn[i].disabled = "true"; playerBtn2.push(btn[i].id); } click++; }); }

var btn = document.getElementsByTagName("button");

You declared it once and every time when you executing this:

playerBtn1.push(btn[i])

your passing reference to same html button (I suppose you have couple of them) every time.

You can try to this instead:

playerBtn1.push(btn[i].cloneNode(true))

Ref: https://www.w3schools.com/jsref/met_node_clonenode.asp

Problem solved

 var playerBtn1 = []; var playerBtn2 = []; var click = 0; var btn = document.getElementsByTagName("button"); for(let i = 0; i <btn.length; i++) { btn[i].addEventListener("click", () => { if(click % 2 == 0) { btn[i].innerHTML = '<i class="fas fa-times fa-5x"></i>'; btn[i].disabled = "true"; playerBtn1.push(btn[i].id); } else { btn[i].innerHTML = '<i class="far fa-circle fa-4x"></i>'; btn[i].disabled = "true"; playerBtn2.push(btn[i].id); } click++; }); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM