Javascript 如何返回相对HTML表值?

Javascript 如何返回相对HTML表值?,javascript,html,parent-child,Javascript,Html,Parent Child,我有一个HTML表格,在第四列有按钮。我希望能够按下每个按钮,让它返回第二列中的值,但返回同一行 我使用以下代码创建表: 函数loadTableData(){ 对于(i=0;i

我有一个HTML表格,在第四列有按钮。我希望能够按下每个按钮,让它返回第二列中的值,但返回同一行

我使用以下代码创建表:

函数loadTableData(){
对于(i=0;i<7;i++){
let row=table.insertRow();
设刻度=行插入单元格(0);
let note=行insertCell(1);
设chord=row.insertCell(2);
让播放=行插入单元格(3);
scale.innerHTML=degChoice[i]
note.innerHTML=finalArray[i];
chord.innerHTML=chordChoice[i];
play.innerHTML='play Chord'
}
}
表格值是根据其他标准生成的(该零件的工作状态良好)

这是我用来调用行中第二个单元格的值的代码:

函数playAudio(){
var firstCell=this.parentNode.parentNode.childNodes[1].nodeValue;
警报(第一单元);
}

不管我怎么做,我都不能返回第二个单元格的值。有人对此有什么建议吗?

您将事件处理程序分配错了。通常,您应该避免在…属性上使用
,但如果您这样做,则需要注意如何为
赋值

它是在
onclick
中定义的,但不是在您的函数
playAudio
中定义的,因此您需要传递它:

play.innerHTML = '<button onclick="playAudio(this)">Play Chord</button>'
但是,如果您直接将其指定为事件处理程序,您也可以在
playAudio
中使用
this
,但随后需要将按钮创建为DOM元素:

const button = document.createElement("button");
button.textContent = "Play Chord"; // Use textContent instead of innerHtml when assigning plain text
button.addEventListener("click", playAudio); // or: button.onclick = playAudio;
play.appendChild(button);
现在您可以在
playAudio
中使用
this
。或者,更好地访问事件对象作为
playAudio
中的第一个参数:

function playAudio(event){
  var button = event.target; // or: var button = this;
  var firstCell = button.parentNode.parentNode.childNodes[1].nodeValue;
  alert(firstCell);
}
事件简介:

function playAudio(event){
  var button = event.target; // or: var button = this;
  var firstCell = button.parentNode.parentNode.childNodes[1].nodeValue;
  alert(firstCell);
}