我制作了一个由SQL数据库填充的表。使用CSS我做到了,当我将鼠标悬停在表格行上时,它会突出显示。当我单击表行(记录)时,我想获取该记录的ID并将其放在一个变量中,该变量可用于更新记录或删除它。
echo "<table>";
echo "<tr>";
echo "<th>".'ID'."</th>";
echo "<th>".'Username'."</th>";
echo "<th>".'Name'."</th>";
echo "<th>".'Role'."</th>";
echo "</tr>";
foreach($result as $pers)
{
echo "<tr>";
echo "<td>".$pers->id."</td>
<td>".$pers->username."</td>
<td>".$pers->name."</td>
td>".$pers->role."</td>";
echo "</tr>";
}
echo "</table>";
在上面您可以看到创建表的代码,它可以正常工作,我只需要一种获取id的方法。
答案 0 :(得分:1)
我认为最佳做法是: 将数据属性赋予“ tr”元素:
echo "<tr data-id='".$pers->id."'>";
...
echo "</tr>";
您可以在点击后收到ID:
$( "tr" ).click(function() {
var id = $(this).attr('data-id');
})
答案 1 :(得分:0)
希望这会有所帮助。单击后,它将ID发送到控制台。源代码中的文档。
/* Put all rows in an array */
const rows = [...document.getElementsByTagName("tr")];
/* Assign event listener to each row */
rows.map(row => row.addEventListener("click", () => {
/* Return the first element */
const id = row.querySelector("td");
console.log(id.textContent);
}));
tr:hover {
background-color: yellow;
}
<table>
<tr>
<td>1</td>
<td>User name 1</td>
<td>Name 1</td>
<td>Role 1</td>
</tr>
<tr>
<td>2</td>
<td>User name 2</td>
<td>Name 2</td>
<td>Role 2</td>
</tr>
<tr>
<td>3</td>
<td>User name 3</td>
<td>Name 3</td>
<td>Role 3</td>
</tr>
</table>
答案 2 :(得分:0)
要在PHP中使用JS数据,可以使用Jquery ajax调用。
$( "tr" ).click(function() {
var id = $(this).first("td").html(); // now you have it in JS available
$.ajax({
url: "yourfile.php", // you can also send it to the php file that updates or deletes the record
data: {"id": id},
type: 'POST',
success : function(data) { }
});
});
然后输入您的PHP代码:
<?php
if(isset($_POST['id'])){
// session id now has your selected id as value.
$_SESSION['id'] = $_POST['id'];
}
else{
unset($_SESSION['id']); // unset session id every time the page reloads
echo "<table>";
echo "<tr>";
echo "<th>".'ID'."</th>";
echo "<th>".'Username'."</th>";
echo "<th>".'Name'."</th>";
echo "<th>".'Role'."</th>";
echo "</tr>";
foreach($result as $pers)
{
echo "<tr>";
echo "<td>".$pers->id."</td>
<td>".$pers->username."</td>
<td>".$pers->name."</td>
<td>".$pers->role."</td>";
echo "</tr>";
}
echo "</table>";
}
然后,当您更新数据库中的一行时,您可以访问$_SESSION['id']
,因为每次您单击tr
时它都会更改。