如何在单击按钮时更改整行的颜色

How to change the color of the entire row on click of button

本文关键字:颜色 单击 按钮      更新时间:2023-09-26

你好,我是javascript/jquery的新手。我有这个页面,用户可以接受或拒绝请求。我想根据按下的按钮更改整行的颜色。如果按下Accept按钮,则整行应变为红色&"拒绝"按钮变为绿色。

<html>
<head>
    <title>MRA</title>
    <script type="text/javascript">
    function Accept() {
        alert("You have Accepted the Request!!");
    }
    function Reject() {
        alert("You have Rejected the Request!!");
    }
    </script>
</head>
<body>
    <h1 align="center">Book</h1>
    <table align="center" width="100%">
        <tr>
            <td>
<?php
$result = mysqli_query($conn,"SELECT * from table  ");
echo "
    <table border='1' id='mytable' width='100%'>
        <tr>
            <th>Id</th>
            <th>User Name</th>
            <th>Purpose</th>
            <th>Attendee</th>
            <th>Date </th>
            <th>StartTime</th>
            <th>EndTime</th>
            <th>Response</th>
        </tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td align='center'><input type='text' readonly size='1' name='textid' value=". $row['id']. "></td>";
    echo "<td align='center'>" . $row['name'] . "</td>";
    echo "<td align='center'>" . $row['purpose'] . "</td>";
    echo "<td align='center'>" . $row['attendee'] . "</td>";
    echo "<td align='center'>" . $row['date'] . "</td>";
    echo "<td align='center'>" . $row['starttime'] . "</td>";
    echo "<td align='center'>" . $row['endtime'] . "</td>";
    echo "<td align='center'>" . '<input type="button" value="Accept" name="txtaccept" onclick="Accept()">&nbsp;&nbsp;&nbsp;<input type="button" value="Reject" name="txtreject" onclick="Reject()">' . "</td>";
    echo "</tr>";
}
echo "</table>";
?>
            </td>
        </tr>
    </table>
</body>
</html>

用于脚本部分:

<script type="text/javascript">
function Accept(el)
{
   var tr = el.parentNode.parentNode; //tr
   tr.className = "accepted";
}
function Reject(el)
{
   var tr = el.parentNode.parentNode; //tr
   tr.className = "rejected";
}
</script>

对于css部分:

<style type="text/css">
table { border-collapse: collapse; } //to remove cell spacings
table td { padding: 2px; }
tr.accepted, tr.accepted td { background-color: green; }
tr.rejected, tr.rejected td { background-color: red; }
</style>

对于html部分:

onclick="Accept(this)" 

onclick="Reject(this)" //to pass the input elements to the functions

在body标记结束之前编写以下代码:

    <script type="text/javascript">
    $(document).ready(function() {
       $("input[name=txtaccept]").on("click", function() {
         $( this ).parent().parent().css( "background-color", "red" );
       });
       $("input[name=txtreject]").on("click", function() {
         $( this ).parent().parent().css( "background-color", "green" );
       });
    });
    </script>
    </BODY>