我有一个HTML表格,第四列有按钮。我希望能够按下每个按钮并让它返回第二列中的值,但同一行。
我使用以下代码创建表:
function loadTableData() {
for (i=0; i < 7; i++) {
let row = table.insertRow();
let scale = row.insertCell(0);
let note = row.insertCell(1);
let chord = row.insertCell(2);
let play = row.insertCell(3);
scale.innerHTML = degChoice[i]
note.innerHTML = finalArray[i];
chord.innerHTML = chordChoice[i];
play.innerHTML = '<button onclick="playAudio()">Play Chord</button>'
}
}
表值是根据其他条件生成的(这部分工作正常)。
这是我用来尝试调用行中第二个单元格的值的代码:
function playAudio(){
var firstCell = this.parentNode.parentNode.childNodes[1].nodeValue;
alert(firstCell);
}
无论我尝试什么,我都无法返回第二个单元格值。有人对此有任何建议吗?
您错误地分配了事件处理程序。通常,您应该避免使用on...
属性,但如果这样做,则需要注意如何为this
分配值。
它是在onclick
内部定义的,但不是在函数playAudio
中定义的,所以你需要传递它:
play.innerHTML = '<button onclick="playAudio(this)">Play Chord</button>'
function playAudio(button){
var firstCell = button.parentNode.parentNode.childNodes[1].nodeValue;
alert(firstCell);
}
但是,如果您直接将其分配为事件处理程序,则可以在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);
}
事件归纳:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events