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

时间:2015-03-23 08:34:07

标签: javascript jquery

您好我是javascript / jquery的新手。我有这个页面,用户将接受或拒绝该请求。我想根据按下的按钮更改整行的颜色。如果按下“接受”按钮,则整行应更改为红色&用于拒绝按钮更改为绿色。

<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>

2 个答案:

答案 0 :(得分:0)

在您的正文标记结束之前编写以下代码:

    <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>

答案 1 :(得分:0)

脚本部分:

<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>

for html part:

onclick="Accept(this)" 

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