我是JavaScript的新用戶。我想添加onclick事件到表格行。我沒有使用JQuery。JavaScript添加表格行onclick事件
我循環通過行並使用閉包來確保每行有外部函數的狀態。 循環工作。使用警報,我看到爲每次迭代分配的功能。但是當我點擊該行時,不會顯示任何提示。 下面是可以加載的HTML和代碼。
爲什麼表格行事件不起作用?
<!doctype html>
<html lang="en">
<body>
<script>
function example4() {
var table = document.getElementById("tableid4");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
var curRow = table.rows[i];
//get cell data from first col of row
var cell = curRow.getElementsByTagName("td")[0];
curRow.onclick = function() {
return function() {
alert("row " + i + " data="+ cell.innerHTML);
};
};
}
}
function init() { example4(); }
window.onload = init;
</script>
<div>
Use loop to assign onclick handler for each table row in DOM. Uses Closure.
<table id="tableid4" border=1>
<tbody>
<tr><td>Item one</td></tr>
<tr><td>Item two</td></tr>
<tr><td>Item three</td></tr>
</tbody>
</table>
</div>
</body>
</html>
你的函數內返回的功能。這需要'onclick'中的另一個函數來調用返回的函數。 – jeremy
這個問題與封閉無關。 – Mathletics
@Mathletics:我使用閉包,因爲我希望事件返回被點擊的行。在早期版本的代碼中,我總是得到第3行總是返回。我的理解是封閉將解決這個問題。 –