用于添加表行onclick事件的JavaScript
我是Javascript的新手。我想将onclick事件添加到表行。我没有使用JQuery。
I'm new to Javascript. I want to add onclick events to table rows. I'm not using JQuery.
我循环遍历行并使用闭包来确保每行都有外部函数的状态。
循环工作。使用警报,我看到为每次迭代分配的功能。但是当我单击该行时,不会显示任何警报。
下面是可以加载的HTML和代码。
I loop thru the rows and use a closure to make sure I have the state of the outer function for each row. The looping works. Using alerts, I see the function being assigned for each iteration. But when I click the row, no alert is displayed. Below is the HTML and code that can be loaded.
为什么表行事件不起作用?
Why are the table row events not working?
<!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>
这似乎是规范的方式
function example4() {
var table = document.getElementById("tableid4");
var rows = table.rows; // or table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
rows[i].onclick = (function() { // closure
var cnt = i; // save the counter to use in the function
return function() {
alert("row"+cnt+" data="+this.cells[0].innerHTML);
}
})(i);
}
}
window.onload = function() { example4(); }
更新:@ParkerSuperstar建议不需要i in(i)。
我没有对此进行测试,但他的小提琴似乎有效。
UPDATE: @ParkerSuperstar suggested that the i in (i) is not needed. I have not tested this but his fiddle seems to work.