如何向表中添加包含某些事件和函数的行
我有一个问题:
<html>
<head>
<script type ="text/javascript">
var add=null;
function throw() {
var artist = document.getElementById("artist").value;
var title = document.getElementById("title").value;
var label = document.getElementById("label").value;
newRow = document.createElement("tr onclick='showRow(this)");
newRow.innerHTML = "<td>" + artist + "</td>" + "<td>" + title + "</td>" + "<td>"
+ label + "</td>";
add = document.getElementById("tabelkaa");
add.appendChild(newRow);
}
function showRow(x) {
alert("Row index is: " + x.rowIndex);
}
window.onload = function () {
var plus = document.getElementById("plus");
plus.addEventListener("click", throw);
}
</script>
</head>
<body>
<div id="info">
<p>Artist <input type ="text" id="artist"> </p>
<p> Title <input type ="text" id="title"> </p>
<p>Label <input type ="text" id="label"> </p>
<input type="submit" value="-" id="minus">
<input type="submit" value="+" id="plus"> <br/>
</div>
<div id ="tabelka">
<table id="tabelkaa" border="5">
</table>
</div>
</body>
我试图添加&#39; onclick&#39;在每一行,因为我想chceck并显示确切的结果。
很抱歉,如果对该帖子有一些评论,但这是我的第一次。
答案 0 :(得分:0)
首先你必须更改功能名称,你不能用户“抛出”因为它是javascript中的保留字,请参阅https://www.w3schools.com/js/js_reserved.asp
var add = null;
function throwFunc() {
var artist = document.getElementById("artist").value;
var title = document.getElementById("title").value;
var label = document.getElementById("label").value;
newRow = document.createElement("tr");
newRow.onclick = function () {
showRow(this)
};
newRow.innerHTML = "<td>" + artist + "</td>" + "<td>" + title + "</td>" + "<td>" + label + "</td>";
add = document.getElementById("tabelkaa");
add.appendChild(newRow);
}
function showRow(x) {
alert("Row index is: " + x.rowIndex);
}
window.onload = function () {
var plus = document.getElementById("plus");
plus.addEventListener("click", throwFunc);
}
注意:Jquery更适合DOM操作