简体   繁体   English

如何使用 HTML onclick 事件传递数组索引

[英]How to pass array index with HTML onclick event

This function takes an argument (an object containing containing the player's attributes)这个 function 接受一个参数(一个包含玩家属性的 object)

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 循环创建了一个 HTML 表,其中包含您可以从中 select 的所有玩家。

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 .问题是当onclick收到i时, alert()返回undefined However, it works as expected when I give it [0] , so I know that logic is working.但是,当我给它[0]时,它会按预期工作,所以我知道逻辑是有效的。 Regardless, it must receive i in order for it to be purposeful.无论如何,它必须接收i才能使其有目的。

<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.您是否将 object 放在字符串中,而不是仅i的值。
That problably was ending like那可能是这样结束的

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

So go with this:所以 go 用这个:

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

Or using template litterals (which I suggest you to explore) that would be:或者使用模板litterals (我建议你探索),这将是:

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>`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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