我正在尝试解决这个问题。第一步是单击第一个按钮后创建一个表。稍后,该表​​被创建,并且一行具有另一个按钮,该按钮应从参数开始另一个函数play()。对于此示例,我只想在控制台中显示就绪,但这是未定义的。当我通过仅在函数外部的console.log调用此函数时,即可正常工作。通过按钮调用功能播放有什么问题?

<table class="table">
  <tr>
            <th>Team A</th>
            <th>Team B</th>
            <th></th>
        </tr>
</table>
  <button onclick="create()">Create next Match</button>

const table = document.querySelector('.table');

const teams=[{
  name: 'Real',
  point: 10
},
            {
  name: 'Barca',
  point: 20
}]

function create(){
  table.innerHTML += `
<tr id="r1m1">
            <td id="host">${teams[0].name}</td>
            <td id="guest">${teams[1].name}</td>
            <td id="host_score"></td>
            <td id="guest_score"></td>
            <td><button onclick="play(${teams[0]},${teams[1]})">Play</button></td>
        </tr>`
}

function play(a,b){
  console.log("ready");
}

console.log(play(teams[0],teams[1]))

最佳答案

不要使用模板替换,就像直接在onclick中引用变量一样,就像在顶级代码中调用play()一样。

function create(){
  table.innerHTML += `
<tr id="r1m1">
    <td id="host">${teams[0].name}</td>
    <td id="guest">${teams[1].name}</td>
    <td id="host_score"></td>
    <td id="guest_score"></td>
    <td><button onclick="play(teams[0],teams[1])">Play</button></td>
</tr>`
}

10-07 13:34
查看更多