You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery动态表格默认加载2017数据问题求助

Fix: Default 2017 Data Load on Page Initialization

Hey there! The problem you're facing is that your table-rendering code only runs when the dropdown selection changes. That's why nothing shows up when the page first loads—there's no trigger to generate the table with your default 2017 data. Let's refactor your code to reuse the table-building logic and fix this issue.

Step-by-Step Explanation

  1. Extract the table generation logic into a reusable function: This way we can call it both on page load and when the dropdown changes.
  2. Call the function immediately after fetching JSON data: This will render the default 2017 data right when the page loads.
  3. Simplify the dropdown change handler: Just grab the selected year and call our reusable function again.

Modified jQuery Code

$(document).ready(function (){
 let url = "students.json";
 $.getJSON(url, function(response){
   // Reusable function to render the student table
   function renderStudentTable(entryYear) {
     let tableHTML = '<table>\
       <tr>\
         <th>Firstname</th>\
         <th>Entry year</th>\
       </tr>';
     
     $.each(response, function(index, student){
       if (student.entry_year === entryYear){
         tableHTML += '<tr>\
           <td>'+student.name+'</td>\
           <td>'+student.entry_year+'</td>\
         </tr>';
       }
     });
     
     tableHTML += '</table>';
     $('#dynamicTable').html(tableHTML);
   }

   // Render default 2017 data on page load
   const defaultYear = "2017";
   renderStudentTable(defaultYear);

   // Update table when dropdown changes
   $("select.year").change(function(){
     const selectedYear = $(this).val(); // Simplified way to get selected value
     renderStudentTable(selectedYear);
   });
 });
});

Your HTML Code (No Changes Needed)

<form>
 <select class="year">
   <option value="2017" selected="selected">2017</option>
   <option value="2018">2018</option>
   <option value="2019">2019</option>
 </select>
</form>
<div id="dynamicTable">
 <!-- the dynamic table will go in here-->
</div>

Key Improvements

  • Code Reusability: By moving the table-building code into a function, we avoid repeating ourselves and make future changes easier.
  • Simplified Value Retrieval: Using $(this).val() is a cleaner way to get the selected dropdown value instead of traversing to the child option.
  • Initial Render: Calling renderStudentTable(defaultYear) right after fetching the JSON ensures the table loads with 2017 data as soon as the page is ready.

Now when your page loads, the 2017 student data will automatically populate the table, and the dropdown will still work as expected when you switch between years.

内容的提问来源于stack exchange,提问作者user1693026

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:56:49