简体   繁体   中英

How to pass array index with HTML onclick event

This function takes an argument (an object containing containing the player's attributes)

const yourTeam = [];

function selectingYourTeam(player) {
  yourTeam.push(player);
  alert(yourTeam[0].name);
  return;
}

This for loop creates an HTML table, that contains all the players you can select from.

for (i = 0; i < playerPool.length; i++) {
  document.write('<tr><td>' + playerPool[i].name + '</td><td>' + playerPool[i].region + 
  '</td><td>' + playerPool[i].skills["Offence"] + '</td><td>' +   
  playerPool[i].skills["Defence"]
  + '</td><td>' + playerPool[i].playerID + '</td><td><button type="button"
  onclick="selectingYourTeam(playerPool[0])">Select Player</button></td></tr>');
}   

The problem is that when onclick receives i the alert() returns undefined . However, it works as expected when I give it [0] , so I know that logic is working. Regardless, it must receive i in order for it to be purposeful.

<button type="button" onclick="selectingYourTeam(playerPool[0])">Select Player</button>

What was wrong with

'<button type="button" onclick="selectingYourTeam(' + playerPool[i] + ')">Select Player</button>'

is you were putting the object inside the string, instead of the value of i only.
That problably was ending like

<button type="button" onclick="selectingYourTeam(Object[object])">Select Player</button>

So go with this:

'<button type="button" onclick="selectingYourTeam(playerPool[' + i + '])">Select Player</button>'

Or using template litterals (which I suggest you to explore) that would be:

document.write(`
<tr><td>
  ${playerPool[i].name}
</td><td>
  ${playerPool[i].region}
</td><td>
  ${playerPool[i].skills["Offence"]}
</td><td>
  ${playerPool[i].skills["Defence"]}
</td><td>
  ${playerPool[i].playerID}
</td><td>
  <button type="button" onclick="selectingYourTeam(playerPool[${i}])">Select Player</button>
</td></tr>`);

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