jQuery 如何使用jquery获取表格中任何位置的表格单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18874185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get table cell values any where in the table using jquery
提问by user244394
I have the following table that returns the each cell value when clicked using javascript?
我有下表,当使用 javascript 单击时返回每个单元格的值?
How can i do the same using jquery?
我如何使用 jquery 做同样的事情?
<script language="javascript">
var tbl = document.getElementById("tblMain");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
</script>
<table align="center" id="tblMain" border="1" style="cursor: pointer;">
<tr>
<td>
R1C1
</td>
<td>
R1C2
</td>
<td>
R1C3
</td>
<td>
R1C4
</td>
</tr>
<tr>
<td>
R2C1
</td>
<td>
R2C2
</td>
<td>
R2C3
</td>
<td>
R2C4
</td>
</tr>
<tr>
<td>
R3C1
</td>
<td>
R3C2
</td>
<td>
R3C3
</td>
<td>
R3C4
</td>
</tr>
<tr>
<td>
R4C1
</td>
<td>
R4C2
</td>
<td>
R4C3
</td>
<td>
R4C4
</td>
</tr>
</table>
回答by Alvaro
Try this:
尝试这个:
$('#tblMain').find('td').click(function(){
alert($(this).text());
});
Living demo: http://jsfiddle.net/pf5cL/
现场演示:http: //jsfiddle.net/pf5cL/
回答by tymeJV
How about:
怎么样:
$("#tblMain tr td").click(function() {
var content = $(this).text();
console.log(content); //Cell text
});
回答by hsz
Try with:
尝试:
$(document).ready(function(){
var getval = function(html) {
alert(html);
}
$('#tblMain td').on('click', function(){
getval($(this).html());
});
});
回答by Rory McCrossan
Try this:
尝试这个:
$(function() {
$('#tblMain td').click(function() {
alert($(this).html()); // or .text()
});
});
jQuery will internally iterate through all the cells for you, so you don't need any looping code at all.
jQuery 将在内部为您遍历所有单元格,因此您根本不需要任何循环代码。