Javascript 通过单击获取一行中的 HTML 表格单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14051821/
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
Get HTML table cells values in a rows by clicking on it
提问by Luke
How can I get values of TDs inside an HTML table?
如何在 HTML 表中获取 TD 的值?
i.e.
IE
| ID | cell 1 | cell 2 |
| 1 | aaaa | a2a2a2 |
| 2 | bbbb | b2b2b2 |
| 3 | cccc | c2c2c2 |
So now if I click on the cell value: "bbbb" I want to get all the values of selected row:
所以现在如果我点击单元格值:“bbbb”我想获取所选行的所有值:
$id='2'; $cell_1='bbbb'; $cell_2='b2b2b2';
NOTE:I'd like to use JavaScript and not jQuery.
注意:我想使用 JavaScript 而不是 jQuery。
回答by Adil
You can use event.target.innerText for javascript and $(event.target).text() for jQuery, jQuery is preferred solution as it handles cross browser competibilities.
您可以将 event.target.innerText 用于 javascript 和 $(event.target).text() 用于 jQuery,jQuery 是首选解决方案,因为它处理跨浏览器的兼容性。
Using only javascript
仅使用 javascript
Html
html
<table id="tableID" onclick="myFun(event)" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>?
Javascript
Javascript
function myFun(e){
alert(e.target.innerText); //current cell
alert(e.target.parentNode.innerText); //Current row.
}?
Using jQuery
使用 jQuery
Html
html
<table id="tableID" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>?
Javascript
Javascript
$('#tableID').click(function(e){
alert($(e.target).text()); // using jQuery
})
回答by AmGates
Hope This helps you. It contains cross browser script.
希望这对你有帮助。它包含跨浏览器脚本。
<html>
<head>
<script type="text/javascript">
function myFun(e){
if(!e.target)
alert(e.srcElement.innerHTML);
else
alert(e.target.innerHTML);
}
</script>
</head>
<body>
<table id="tableID" onclick="myFun(event)" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
</body>
</html>
回答by Bhavin Rana
回答by Rajesh
Use of jquery will be easy..
使用 jquery 会很容易..
$("#tableId").find("td").click(function(event){
var listOfCell=$(this).siblings();
for(i=0;i<listOfCell.length;i++){
alert($(listOfCell[i]).text());
}
});

