简体   繁体   English

功能中的按钮onclick

[英]Button onclick in function

I'm trying to solve this problem.我正在努力解决这个问题。 First step is create a table after clicking on first button.第一步是单击第一个按钮后创建一个表。 Later the table is creating and one row has another button which should starting another function play() with arguments.后来表格正在创建,一行有另一个按钮,它应该启动另一个带参数的函数 play() 。 For this example I just want to display ready in console but this is undefined.对于这个例子,我只想在控制台中显示就绪,但这是未定义的。 When I call this function by simply console.log outside the function then is working correctly.当我在函数外简单地通过 console.log 调用这个函数时,它就可以正常工作了。 What is wrong with calling function play by button?按按钮调用功能播放有什么问题?

<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]))

You are mashing strings together, so teams[0] gets converted to [object Object] which not only doesn't contain the data you want, but also isn't syntactically valid JavaScript.您将字符串混合在一起,因此teams[0]被转换为[object Object] ,它不仅不包含您想要的数据,而且在语法上也不是有效的 JavaScript。

You might be able to manage with onclick="play(teams[0],teams[1])" but scope might trip you up (as teams and play must be globals, which are best avoided in general).您可能可以使用onclick="play(teams[0],teams[1])"但范围可能会让您失望(因为teamsplay必须是全局变量,通常最好避免使用)。

In general, your should use DOM methods like createElement , addEventListener and appendChild instead.通常,您应该使用 DOM 方法,例如createElementaddEventListenerappendChild

Don't use template substitution, just refer to the variables in directly in the onclick , just like when you call play() in the top-level code.不要使用模板替换,直接在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>`
}

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

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