所有单元格中的Javascript onClick事件
问题描述:
我正在学习JavaScript而且我的经验并不多。
但是我正在创建一个HTML表格,我想在每个表格单元格(< td>
)中添加一个onClick事件。
I'm learning JavaScript and I've not that much experience.
But I'm making a HTML table and I want to add in every table cell (<td>
) a onClick event.
<table id="1">
<tr>
<td onClick="tes()">1</td><td onClick="tes()">2</td>
</tr>
<tr>
<td onClick="tes()">3</td><td onClick="tes()">4</td>
</tr>
</table>
是否有另一种方法可以在每个单元格中执行此事件?
Is there another way to do this event in every cell?
答
有两种方法:
var cells = table.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
cells[i].onclick = function(){tes();};
}
以及使用jQuery的另一种方式:
and the other way using jQuery:
$('td').click(function(){tes();});
upd:
要准确得到所需内容,首先必须选择表格,因此,对于第一个选项:
To get exactly what is needed, firstly the table must be selected, so, for the first option:
var table = document.getElementById('1');
var cells = table.getElementsByTagName("td");
...
第二,jQ选择器应如下所示:
and for the second, the jQ selector should be like this:
$('#1 td')