我试图在单击时更改我的tbody 中表格行的背景颜色

问题描述 投票:0回答:0

我是一名一年级学生,正在创建一个函数,以便在单击表格行或 td 单元格时突出显示并更改“populateStaffTable”tbody 表格行中的背景颜色。尽管尝试了各种功能和代码放置,但我仍无法使其工作。有人可以帮助我吗?我已经提供了 HTML 和 JS 文件。请注意,我还没有完成,而且我在开发方面也没有太多经验,所以请不要严厉地评判我。

JS

//Staff Class
class Staff {
    constructor(data) {
        this.id = data.login.uuid;
        this.name = `${data.name.first} ${data.name.last}`;
        this.surname = data.name.last;
        this.email = data.email;
        this.image = data.picture.large;
        this.status = 'In';
        this.outTime = null;
        this.duration = null;
        this.expectedReturnTime = null;
        console.log('Staff instance:', this); // Add this line to inspect the created instance
      }
    
  
    clockOut(durationInMinutes) {
      this.status = 'Out';
      this.outTime = new Date();
      this.duration = durationInMinutes;
      this.expectedReturnTime = new Date(this.outTime.getTime() + durationInMinutes * 60000);
    }
  
    clockIn() {
      this.status = 'In';
      this.outTime = null;
      this.duration = null;
      this.expectedReturnTime = null;
    }
  
    getDurationString() {
      const durationInHours = Math.floor(this.duration / 60);
      const remainingMinutes = this.duration % 60;
      if (remainingMinutes > 0) {
        return `${durationInHours} hour(s) and ${remainingMinutes} minute(s)`;
      } else {
        return `${durationInHours} hour(s)`;
      }
    }
  
    isOutOfOffice() {
      if (this.status === 'Out' && new Date() > this.expectedReturnTime) {
        return true;
      } else {
        return false;
      }
    }
  
    getStatus() {
      return this.status;
    }
  
    getClockOutTime() {
      return this.outTime? this.outTime.toLocaleTimeString() : '';
        }
    }

  //StaffDashboard class
  class StaffDashboard {
    constructor() {
      this.staffMembers = new Map();
    }
  
    async loadStaffMembers() {
        const response = await fetch('https://randomuser.me/api/?results=5');
        const data = await response.json();
        console.log('API response:', data); // Add this line to inspect the API response
        data.results.forEach(result => {
          const staffMember = new Staff(result);
          this.staffMembers.set(staffMember.id, staffMember);
        });
        this.populateStaffTable();
      }
  
    getStaffMember(id) {
      return this.staffMembers.get(id);
    }
  
    updateStaffMember(id, staffMember) {
      this.staffMembers.set(id, staffMember);
      this.populateStaffTable();
    }
  
    populateStaffTable() {
        const tableBody = document.getElementById('populateStaffTable');
        tableBody.innerHTML = '';
        this.staffMembers.forEach(staffMember => {
          const row = document.createElement('tr');
          row.setAttribute('data-staff-id', staffMember.id);
          row.innerHTML = `
            <td><img src="${staffMember.image}" alt="${staffMember.name} ${staffMember.surname}" class="avatar"></td>
            <td>${staffMember.name}</td>
            <td>${staffMember.surname}</td>
            <td>${staffMember.email}</td>
            <td>${staffMember.getStatus()}</td>
            <td>${staffMember.getClockOutTime()}</td>
            <td>${staffMember.duration? staffMember.getDurationString() : ''}</td>
            <td>${staffMember.expectedReturnTime? staffMember.expectedReturnTime.toLocaleTimeString() : ''}</td>`;
        tableBody.appendChild(row);
      });
    }
}

// Global variables and functions 
const staffDashboard = new StaffDashboard();

async function staffUserGet() {
  await staffDashboard.loadStaffMembers();
}

staffUserGet();

function selectStaffMember(event) {
    const tableRows = document.querySelectorAll('#populateStaffTable tr');
    tableRows.forEach(row => row.classList.remove('selected-row'));
    event.target.closest('tr').classList.add('selected-row');
}

document.getElementById('populateStaffTable').addEventListener('click', selectStaffMember);

  function staffOut() {
    const selectedRow = document.querySelector('.selected-row');
    if (!selectedRow) {
      alert('Please select a staff member from the table.');
      return;
    }
    const staffId = selectedRow.getAttribute('data-staff-id');
    const staffMember = staffDashboard.getStaffMember(staffId);
    const durationInMinutes = prompt(`Enter out-time for ${staffMember.name} ${staffMember.surname}'s in minutes:`);
    if (durationInMinutes) {
      staffMember.clockOut(parseInt(durationInMinutes, 10));
      staffDashboard.updateStaffMember(staffId, staffMember);
      selectedRow.classList.remove('bg-success'); // Remove the bg-success class
    }
  }

  function staffIn() {
    const selectedRow = document.querySelector('.selected-row');
    if (!selectedRow) {
      alert('Please select a staff member from the table.');
      return;
    }
    const staffId = selectedRow.getAttribute('data-staff-id');
    const staffMember = staffDashboard.getStaffMember(staffId);
    staffMember.clockIn();
    staffDashboard.updateStaffMember(staffId, staffMember);
    alert(`You are clocking in: ${staffMember.name} ${staffMember.surname}`);
    selectedRow.classList.remove('bg-success'); // Remove the bg-success class
  }

// Digital Clock
function digitalClock() {
  const now = new Date();
  const options = { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' };
  const clock = now.toLocaleDateString('en-US', options);
  document.getElementById('clock').textContent = clock;
  setTimeout(digitalClock, 1000);
}

digitalClock();

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WeDeliverTECH Reception Management</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Bootstrap CSS -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#">Dashboard</a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Inventory
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                        <a class="dropdown-item" href="#">Search</a>
                        <a class="dropdown-item" href="#">Add</a>
                        <a class="dropdown-item" href="#">Remove</a>
                    </div>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Orders
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                        <a class="dropdown-item" href="#">Search</a>
                        <a class="dropdown-item" href="#">Add</a>
                        <a class="dropdown-item" href="#">Remove</a>
                    </div>
                </li>
            </ul>
        </div>
    </nav>
    <span>
        <main>
        <div class="companyLogo">
            <div class="row">
                <div class="col">
                    <!-- WeDeliverTECH logo -->
                    <img src="C:\Users\jonas\Noroff Studie\Git\SP1\jan24ft-sp1-ca-1-skybulk3r\Company logo.png" class="logo" alt="wideliver_logo.png">
                </div>
            </div>
        </div>
    </span>
    <h2 class="heading">Reception Management Dashboard Staff</h2>
    <div class="table-wrapper">
        <table class="table" id="staffTable">
            <thead>
                <tr>
                    <th>Picture</th>
                    <th>Name</th>
                    <th>Surname</th>
                    <th>Email address</th>
                    <th>Status</th>
                    <th>Out Time</th>
                    <th>Duration</th>
                    <th>Expected Return Time</th>
                </tr>
            </thead>
            <tbody id="populateStaffTable">
                <!-- Staff members data will be dynamically populated here -->
              </tbody>
        </table>
    </div>
        <!-- Clock In/Out buttons -->
        <div class="btn-toolbar">
    
    <button id="staffOut" class="btn btn-negative" onclick="staffOut()">Out</button>
    <button id="staffIn" class="btn btn-positive" onclick="staffIn()">In</button>
        </div>
       <!-- Delivery Schedule Section -->
<div class="col">
    <h2 class="heading">Delivery Schedule</h2>
    <div class="table-wrapper">
    <!-- Delivery drivers table with Add and Clear buttons -->
    <table class="table">
        <thead>
            <tr>
                <th>Vehicle:</th>
                <th>Name:</th>
                <th>Surname:</th>
                <th>Telephone:</th>
                <th>Address:</th>
                <th>Return Time:</th>
            </tr>
        </thead>
        <tbody id="delivery-table-body">
            <tr>
              <td>
                <select>
                  <option value="car"> Car</option>
                  <option value="motorcycle"> Motorcycle</option>
                </select>
              </td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td>
                <input type="time" />
              </td>
            </tr>
          </tbody>
            <!-- Delivery drivers data will be dynamically populated here -->
        </tbody>
    </table>
</div>
    <div class="btn-toolbar">
    <button type="button" id="add-delivery" class="btn btn-positive">Add</button>
            </div>
        </div>
            </div>
            <!-- Delivery Board Section -->
            <div class="row">
                <div class="col">
                    <h2 class="heading">Delivery Board</h2>
                    <div class="table-wrapper">
                    <!-- Delivery board table -->
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Vehicle</th>
                                <th>Name</th>
                                <th>Surname</th>
                                <th>Telephone</th>
                                <th>Delivery Address</th>
                                <th>Return Time</th> 
                            </tr>
                        </thead>
                        <tbody id="delivery-board-body">
                            <!-- Delivery board data will be dynamically populated here -->
                        </tbody>
                    </table>
                     </div>
                    <div class="btn-toolbar">
                    <button type="button" id="clear-delivery" class="btn btn-negative">Clear</button>
                </div>
            </div>
        </section>
    </main>
    <footer>
        <div class="time">
            <div class="container">
                <div class="row justify-content-end">
                    <div class="col-auto">
                        <span id="clock"></span>
                    </div>
                </div>
            </div>
        </div>
    </footer>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="wdt_app.js"></script>
</body>
</html>
html-table jquery-selectors addeventlistener background-color selectors-api
© www.soinside.com 2019 - 2024. All rights reserved.