萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 向 Bootstrap Modal 動態插入多筆資料完整範例

HTML 結構


<!-- 觸發按鈕 -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#orderDetail" onclick="orderDetail('ORD-20240101')">
  查看訂單詳情
</button>

<!-- Modal -->
<div class="modal fade" id="orderDetail" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">訂單明細</h5>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <table class="table table-bordered">
          <thead>
            <tr><th>商品</th><th>原價</th><th>售價</th></tr>
          </thead>
          <tbody id="orderDetailBody"></tbody>
        </table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">關閉</button>
      </div>
    </div>
  </div>
</div>

JavaScript 邏輯


function orderDetail(orderNo) {
  var $tbody = $('#orderDetailBody');
  
  // 1. 清空舊資料(保留表頭)
  $tbody.empty();

  // 2. 顯示載入中
  $tbody.append('<tr><td colspan="3" class="text-center">載入中...</td></tr>');

  // 3. AJAX 請求
  $.post('/admin/orders/ajax_detail', {order_no: orderNo}, function(res) {
    $tbody.empty(); // 清除載入中
    
    var data;
    try { data = typeof res === 'string' ? JSON.parse(res) : res; }
    catch (e) { $tbody.append('<tr><td colspan="3" class="text-danger">資料格式錯誤</td></tr>'); return; }

    if (!data.length) {
      $tbody.append('<tr><td colspan="3" class="text-center">無明細資料</td></tr>');
      return;
    }

    // 4. 批次插入(DocumentFragment 概念,jQuery 內部優化)
    var rows = [];
    $.each(data, function(i, item) {
      rows.push(
        '<tr>' +
          '<td>' + (item.organize_name || '') + ':' + (item.cate_name || '') + ' -- ' + (item.course_name || '') + '</td>' +
          '<td>' + (item.old_price || 0) + '</td>' +
          '<td>' + (item.sale_price || 0) + '</td>' +
        '</tr>'
      );
    });
    $tbody.append(rows.join(''));
  }).fail(function() {
    $tbody.empty().append('<tr><td colspan="3" class="text-danger">請求失敗</td></tr>');
  });
}

後端回傳資料格式範例 (JSON)


[
  {"organize_name": "數位學院", "cate_name": "前端課程", "course_name": "Vue 3 實戰", "old_price": 3000, "sale_price": 2400},
  {"organize_name": "數位學院", "cate_name": "後端課程", "course_name": "Node.js 進階", "old_price": 3500, "sale_price": 2800}
]

效能與體驗優化建議

  • 事件委派:按鈕改用 $(document).on('click', '[data-order-no]', function(){ orderDetail($(this).data('order-no')); }),支援動態新增按鈕。
  • 快取 Modal 實例:var $modal = $('#orderDetail').modal({show: false}); 避免重複初始化。
  • 大量資料虛擬滾動:超過 100 筆建議使用 clusterize.js 或表格虛擬化。
  • 錯誤狀態樣式:統一錯誤/空狀態/載入中 UI 模板。
copyright © 萬盛學電腦網 all rights reserved