所有单元格中的Javascript onClick事件 [英] Javascript onClick event in all cells
本文介绍了所有单元格中的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')
这篇关于所有单元格中的Javascript onClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文