我正在尝试更新我单击的行所对应的字段,所以如果我单击第二行,我希望底部的字段分别更改,因此名称转到第一个字段,电子邮件转到第二个,等等。然后,如果我点击第一行,那么第一行的数据应显示在那些字段中。
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table style="width:100%">
<tr >
<th id="name">Name</th>
<th id="email">Email</th>
<th id="phone">Phone</th>
<th id="addr">Address</th>
</tr>
<tr id="Row1" onclick="myFunction();">
<td>Jane Doe</td>
<td>Jane@Jane.com</td>
<td>123</td>
<td>US</td>
</tr>
<tr id="Row2" onclick="myFunction();">
<td>John Doe</td>
<td>John@John.com</td>
<td>321</td>
<td>US</td>
</tr>
</table>
<form>
<br><br>
Name Field:
<input type="text" id="Name"> <br><br>
Email Field:
<input type="text" id="Email"><br><br>
Phone Field:
<input type="text" id="Phone"><br><br>
Address Field:
<input type="text" id="Address"><br><br>
</form>
<script>
function myFunction() {
document.getElementById("Name").value = "Name changes!";
document.getElementById("Email").value = "Email changes!";
document.getElementById("Phone").value = "Phone changes!";
document.getElementById("Address").value = "Address changes!";
}
</script>
</body>
</html>
答案 0 :(得分:1)
table, th, td {
border: 1px solid black;
}
&#13;
<script
src="https://code.jquery.com/jquery-3.2.1.js"></script>
<body>
<table style="width:100%">
<tr >
<th id="name">Name</th>
<th id="email">Email</th>
<th id="phone">Phone</th>
<th id="addr">Address</th>
</tr>
<tr id="Row1" onclick="myFunction('Row1');">
<td>Jane Doe</td>
<td>Jane@Jane.com</td>
<td>123</td>
<td>US</td>
</tr>
<tr id="Row2" onclick="myFunction('Row2');">
<td>John Doe</td>
<td>John@John.com</td>
<td>321</td>
<td>US</td>
</tr>
</table>
<form>
<br><br>
Name Field:
<input type="text" id="Name"> <br><br>
Email Field:
<input type="text" id="Email"><br><br>
Phone Field:
<input type="text" id="Phone"><br><br>
Address Field:
<input type="text" id="Address"><br><br>
</form>
<script>
function myFunction(rowid) {
if(rowid=="Row1")
{
$('#Row1').each(function() {
document.getElementById("Name").value = $(this).find("td").eq(0).html();
document.getElementById("Email").value =$(this).find("td").eq(1).html();;
document.getElementById("Phone").value =$(this).find("td").eq(2).html();;
document.getElementById("Address").value = $(this).find("td").eq(3).html();;
});
}
else if(rowid=="Row2")
{
$('#Row2').each(function() {
document.getElementById("Name").value = $(this).find("td").eq(0).html();
document.getElementById("Email").value =$(this).find("td").eq(1).html();;
document.getElementById("Phone").value =$(this).find("td").eq(2).html();;
document.getElementById("Address").value = $(this).find("td").eq(3).html();;
});
}
}
</script>
</body>
&#13;
我想如果你仔细阅读下面的代码,你可以得到一些想法。
我对您现有的代码进行了一些更改。
这里是硬编码的。 你可以用最少的变化使它变得动态。
答案 1 :(得分:1)
您可以使用&#34;此&#34;在TR上指定关键字,然后得到那个TR的孩子