尝试点击HTML单元格并获取该单元格的html数据,将其粘贴到表单字段中,以便在后一个过程中使用。如果我直接编码,我可以将此字段值设置为我想要的任何值:blah = 99;但是,如果我将该硬值更改为变量或单元格内容,则它不起作用。我可以整天提醒它,我只是不能为我的生活获得价值去表格领域。我错过了什么?
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) {
var theTarget;
theTarget = cel.innerHTML;
document.getElementById("status").value = cel.innerHTML;
}
&#13;
<center>
Click on below table cell to find its value.
<br />
</center>
<table align="center" id="tblMain" border="1" style="cursor: pointer;">
<tr>
<td>
R1C1
</td>
<td>
R1C2
</td>
<td>
R1C3
</td>
<td>
R1C4
</td>
</tr>
</table><br><br>
<p align="center"><input name="status" type="text" id="status" style="color: #000; border: #000 1px solid;" size="5">
</p>
&#13;
答案 0 :(得分:2)
有效。只是innerHTML
在实际文本周围有太多空白区域。使用trim()
来摆脱它。
<html>
<head>
<title>Find table cell value on cell (table) click using JavaScript</title>
</head>
<body>
<center>
Click on below table cell to find its value.
<br />
</center>
<table align="center" id="tblMain" border="1" style="cursor: pointer;">
<tr>
<td>
R1C1
</td>
<td>
R1C2
</td>
<td>
R1C3
</td>
<td>
R1C4
</td>
</tr>
</table><br><br>
<p align="center"><input name="status" type="text" id="status" style="color: #000; border: #000 1px solid;" size="5">
</p>
<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) {
var theTarget;
theTarget = cel.innerHTML;
document.getElementById("status").value = cel.innerHTML.trim();
}
</script>
</body>
</html>
&#13;
答案 1 :(得分:1)
您可以使用正则表达式删除字符串cel.innerHTML.replace(/^\s+|\s+$/g,'');
之前和之后的空格,这将在不支持trim()
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) {
var theTarget;
theTarget = cel.innerHTML;
document.getElementById("status").value = cel.innerHTML.replace(/\s/g, "");
}
&#13;
<center>
Click on below table cell to find its value.
<br />
</center>
<table align="center" id="tblMain" border="1" style="cursor: pointer;">
<tr>
<td>
R1C1
</td>
<td>
R1C2
</td>
<td>
R1C3
</td>
<td>
R1C4
</td>
</tr>
</table><br><br>
<p align="center"><input name="status" type="text" id="status" style="color: #000; border: #000 1px solid;" size="5">
</p>
&#13;