包含数据的 Feed 表

Feed table with data

提问人:Lucad 提问时间:11/17/2023 更新时间:11/17/2023 访问量:17

问:

我正在尝试过滤表格以仅显示属于特定州的人。我有我的html,我创建了一个js(API连接),可以检索所有信息并填充表格。在另一个 js 上,我根据 json 为状态创建了一个过滤器。现在我已经填充了表格,我正在尝试根据状态进行过滤。

[html]

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>House of Representatives</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="/assets/css/tgif.css">
  </head>
   
  <body>
    <a class="navbar-brand" href="/pages/home.html">
      <img src="/assets/img/logo.jpg " alt="logo" height="200">
     </a>
    <nav class="navbar navbar-expand-lg navbar-light bg-light custom-navbar">
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav">
          <li class="nav-item active">
            <a class="nav-link" href="/pages/home.html">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Congress 113
            </a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
              <a class="dropdown-item" href="/pages/senate.html">Senate</a>
              <a class="dropdown-item" href="/pages/house.html">House</a>
           </li>
           <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Attendance
            </a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
              <a class="dropdown-item" href="/pages/senate-attendance.html">Senate</a>
              <a class="dropdown-item" href="/pages/house-attendance.html">House</a>
           </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Loyalty
            </a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
              <a class="dropdown-item" href="/pages/senate-loyalty.html">Senate</a>
              <a class="dropdown-item" href="/pages/house-loyalty.html">House</a>
              
            </div>
          </li>
        </ul>
      </div>
    </nav> 
  <body>
  
    <div>   
      <h1>Representatives</h1>
      <p>The major power of the House is to pass federal legislation that affects the entire country, although its bills must also be passed by the Senate and further agreed to by the U.S. President before becoming law (unless both the House and Senate re-pass the legislation with a two-thirds majority in each chamber). The House has some exclusive powers: the power to initiate revenue bills, to impeach officials (impeached officials are subsequently tried in the Senate), and to elect the U.S. President in case there is no majority in the Electoral College.</p>
      <p>Each U.S. state is represented in the House in proportion to its population as measured in the census, but every state is entitled to at least one representative. </p>
          
      <div>
        <p>Filter by Party</p>
        <div class="form-check form-check-inline">
          <input class="form-check-input" type="checkbox" value="" id="republicanCheckbox" checked>
          <label class="form-check-label" for="republicanCheckbox">
            Republican
          </label>
        </div>
        <div class="form-check form-check-inline">
          <input class="form-check-input" type="checkbox" value="" id="democraticCheckbox" checked >
          <label class="form-check-label" for="democraticCheckbox">
            Democratic
          </label>
        </div>
        <div class="form-check form-check-inline">
          <input class="form-check-input" type="checkbox" value="" id="independentCheckbox" checked>
          <label class="form-check-label" for="independentCheckbox">
            Independent
          </label>
        </div>
        
        
        <div class="d-flex justify-content-end align-items-center">
          <div class="mr-2">
            <p class="mb-0">Filter by State</p>
          </div>
          <div class="btn-group">
            <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Select a state
            </button>
            <div class="dropdown-menu dropdown-menu-right scrollable-menu" id="statesDropdown">
             </div> 
        </div>
    </div>
</div>


      <table  data-toggle="table" id="houseTable"  data-click-to-select="true" class="table table-dark">
        <thead>
          <tr>
            <th scope="col">Name</th>
            <th  scope="col">Party</th>
            <th scope="col">State</th>
            <th scope="col">Years in Office</th>
            <th scope="col">Y% Votes with Party</th>
          </tr>
        </thead>
        <tbody>

        </tbody>
      </table>
    </div>
   
    
   
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/poppe[email protected]/dist/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <script src="/import-list-house.js"></script>
<script src="/state-filter.js"></script>

  </body>
  <footer
          class="text-center text-lg-start text-white"
          style="background-color: #1c2331"
          >
    <!-- Section: Social media -->
    <section
             class="d-flex justify-content-between p-4"
             style="background-color: #4dbeff"
             >
      <!-- Left -->
      <div class="me-5">
        <span>Get connected with us on social networks:</span>
      </div>
      <!-- Left -->

      <!-- Right -->
      <div>
        <a href="" class="text-white me-4">
          <i class="fab fa-facebook-f"></i>
        </a>
        <a href="" class="text-white me-4">
          <i class="fab fa-twitter"></i>
        </a>
        <a href="" class="text-white me-4">
          <i class="fab fa-google"></i>
        </a>
        <a href="" class="text-white me-4">
          <i class="fab fa-instagram"></i>
        </a>
        <a href="" class="text-white me-4">
          <i class="fab fa-linkedin"></i>
        </a>
        <a href="" class="text-white me-4">
          <i class="fab fa-github"></i>
        </a>
      </div>
      <!-- Right -->
    </section>
    <!-- Section: Social media -->

    <!-- Section: Links  -->
    <section class="">
      <div class="container text-center text-md-start mt-5">
        <!-- Grid row -->
        <div class="row mt-3">
          <!-- Grid column -->
          <div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
            <!-- Content -->
            <h6 class="text-uppercase fw-bold">Company name</h6>
            <hr
                class="mb-4 mt-0 d-inline-block mx-auto"
                style="width: 60px; background-color: #4dbeff; height: 2px"
                />
            <p>
              Here you can use rows and columns to organize your footer
              content. Lorem ipsum dolor sit amet, consectetur adipisicing
              elit.
            </p>
          </div>
          <!-- Grid column -->

          <!-- Grid column -->
          <div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
            <!-- Links -->
            <h6 class="text-uppercase fw-bold">Products</h6>
            <hr
                class="mb-4 mt-0 d-inline-block mx-auto"
                style="width: 60px; background-color: #4dbeff; height: 2px"
                />
            <p>
              <a href="#!" class="text-white">MDBootstrap</a>
            </p>
            <p>
              <a href="#!" class="text-white">MDWordPress</a>
            </p>
            <p>
              <a href="#!" class="text-white">BrandFlow</a>
            </p>
            <p>
              <a href="#!" class="text-white">Bootstrap Angular</a>
            </p>
          </div>
          <!-- Grid column -->

          <!-- Grid column -->
          <div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
            <!-- Links -->
            <h6 class="text-uppercase fw-bold">Useful links</h6>
            <hr
                class="mb-4 mt-0 d-inline-block mx-auto"
                style="width: 60px; background-color: #4dbeff; height: 2px"
                />
            <p>
              <a href="#!" class="text-white">Your Account</a>
            </p>
            <p>
              <a href="#!" class="text-white">Become an Affiliate</a>
            </p>
            <p>
              <a href="#!" class="text-white">Shipping Rates</a>
            </p>
            <p>
              <a href="#!" class="text-white">Help</a>
            </p>
          </div>
          <!-- Grid column -->

          <!-- Grid column -->
          <div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
            <!-- Links -->
            <h6 class="text-uppercase fw-bold">Contact</h6>
            <hr
                class="mb-4 mt-0 d-inline-block mx-auto"
                style="width: 60px; background-color: #4dbeff; height: 2px"
                />
            <p><i class="fas fa-home mr-3"></i> New York, NY 10012, US</p>
            <p><i class="fas fa-envelope mr-3"></i> [email protected]</p>
            <p><i class="fas fa-phone mr-3"></i> + 01 234 567 88</p>
            <p><i class="fas fa-print mr-3"></i> + 01 234 567 89</p>
          </div>
          <!-- Grid column -->
        </div>
        <!-- Grid row -->
      </div>
    </section>
    <!-- Section: Links  -->

    <!-- Copyright -->
    <div
         class="text-center p-3"
         style="background-color: rgba(0, 0, 0, 0.2)"
         >
      © 2023 Copyright:
      <a class="text-white" href="#"
         >TGIF </a
        >
    </div>
    <!-- Copyright -->
  </footer>
  <!-- Footer -->

</div>
<!-- End of .container -->
</html>
</html>

状态 flter

document.addEventListener('DOMContentLoaded', function () {
  let dropdown = document.getElementById('statesDropdown');

  const url = 'https://gist.githubusercontent.com/mshafrir/2646763/raw/8b0dbb93521f5d6889502305335104218454c2bf/states_hash.json';

  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      let states = Object.values(data);

      // Check if the 'All' option already exists
      let allOption = dropdown.querySelector('a[data-state="All"]');
      if (!allOption) {
        allOption = document.createElement('li');
        allOption.innerHTML = '<a class="dropdown-item" href="#" data-state="All">All</a>';
        dropdown.appendChild(allOption);
      }

      // Add options to the dropdown
      for (let i = 0; i < states.length; i++) {
        let option = document.createElement('li');
        option.innerHTML = `<a class="dropdown-item" href="#" data-state="${states[i]}">${states[i]}</a>`;
        dropdown.appendChild(option);
      }


      
      // Add 'dropdown-menu-right' class to position the dropdown to the right
      dropdown.classList.add('dropdown-menu-right');
    })
    .catch((error) => console.error(error));

  // Add event listener for state selection
  dropdown.addEventListener('click', function (event) {
    event.preventDefault();
    const selectedState = event.target.getAttribute('data-state');
    console.log('Selected State:', selectedState);
  // Set the selected state in the dropdown
  dropdown.setAttribute('data-selected-state', selectedState);

  // Reset the table to its original state
  tableBody.innerHTML = tableBody.getAttribute('data-original-data');

  // Fetch and populate the table based on the selected state
  fetchAndPopulateTable();
});
  });

传真 APi/表

// Declare variables in the global scope
let dropdown;
let tableBody;
let republicanCheckbox;
let democraticCheckbox;
let independentCheckbox;
let url; // Declare url variable in the global scope

function fetchAndPopulateTable() {
  console.log('Fetching and populating table...');
  const selectedState = dropdown.getAttribute('data-selected-state');
  console.log('Selected State:', selectedState);

  fetch(url, {
    method: 'GET',
    headers: {
      'X-API-KEY': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  })
    .then((response) => response.json())
    .then((data) => {
      // Filter members based on selected checkboxes
      let members = data.results[0].members.filter((member) => {
        return (
          (republicanCheckbox.checked && member.party === 'R') ||
          (democraticCheckbox.checked && member.party === 'D') ||
          (independentCheckbox.checked && member.party === 'I')
        );
      });

      // Filter members based on selected state
      if (selectedState && selectedState !== 'All') {
        members = members.filter((member) => member.state === selectedState);
      }

      // Clear existing rows
      tableBody.innerHTML = '';

      // Populate the table with the filtered members
      for (let i = 0; i < members.length; i++) {
        const row = document.createElement('tr');
        const fullName = `${members[i].first_name} ${members[i].last_name}`;
        row.innerHTML = `
          <td><a href="${members[i].url}">${fullName}</a></td>
          <td>${members[i].party}</td>
          <td>${members[i].state}</td>
          <td>${members[i].seniority}</td>
        `;

        tableBody.appendChild(row);
      }
    })
    .catch((error) => console.error(error));
}

document.addEventListener('DOMContentLoaded', function () {
  dropdown = document.getElementById('statesDropdown');
  url = 'https://api.propublica.org/congress/v1/116/house/members.json'; // Set the value of url
  tableBody = document.getElementById('houseTable').getElementsByTagName('tbody')[0];
  tableBody.setAttribute('data-original-data', '');

  // Fetch data and populate the initial table
  fetchAndPopulateTable();

  // Assign event listeners to checkboxes
  republicanCheckbox = document.getElementById('republicanCheckbox');
  democraticCheckbox = document.getElementById('democraticCheckbox');
  independentCheckbox = document.getElementById('independentCheckbox');

  republicanCheckbox.addEventListener('change', fetchAndPopulateTable);
  democraticCheckbox.addEventListener('change', fetchAndPopulateTable);
  independentCheckbox.addEventListener('change', fetchAndPopulateTable);

  // Add event listener for state selection
  dropdown.addEventListener('click', function (event) {
    event.preventDefault();
    const selectedState = event.target.getAttribute('data-state');
    console.log('Dropdown Clicked. Selected State:', selectedState);

    // Set the selected state in the dropdown
    dropdown.setAttribute('data-selected-state', selectedState);

    // Fetch and populate the table based on the selected state
    fetchAndPopulateTable();
  });
});

提前致谢!

JavaScript 数据表

评论


答: 暂无答案