<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
  // 定义全局变量
  var allChecked = false;

  // 添加表标题
  var flag = true;
  $('input[value='添加表标题']').click(function() {
    if (flag) {
      $('#tab1').before('<h2 style='text-align:center'>商品列表</h2>');
      flag = false;
    }
  });

  // 添加样式
  $('input[value='添加样式']').click(function() {
    $('#tab1').addClass('mc');
  });

  // 删除样式
  $('input[value='删除样式']').click(function() {
    $('#tab1').removeClass('mc');
  });

  // 切换样式
  $('input[value='切换样式']').click(function() {
    $('#tab1').toggleClass('mc');
  });

  // 全选复选框
  $('th input[type='checkbox']').click(function() {
    allChecked = !allChecked;
    $('td input[type='checkbox']').prop('checked', allChecked);
  });

  // 行复选框
  $('td input[type='checkbox']').click(function() {
    var checkedNum = $('td input[type='checkbox']:checked').length;
    var totalNum = $('td input[type='checkbox']').length;
    if (checkedNum == totalNum) {
      $('th input[type='checkbox']').prop('checked', true);
      allChecked = true;
    } else {
      $('th input[type='checkbox']').prop('checked', false);
      allChecked = false;
    }
  });

  // 添加行
  $('input[value='添加']').click(function() {
    var $lastTr = $('#tab1 tr:last');
    var lastId = parseInt($lastTr.children('td:eq(1)').text());
    var newId = lastId + 1;
    var newTr = '<tr><td><input type='checkbox'></td><td>' + newId + '</td><td></td><td></td><td><a href=''>删除</a></td></tr>';
    $('#tab1 tr:last').after(newTr);
    allChecked = false;
    $('th input[type='checkbox']').prop('checked', false);
  });

  // 删除行
  $('table').on('click', 'a', function() {
    $(this).parents('tr').remove();
    var checkedNum = $('td input[type='checkbox']:checked').length;
    var totalNum = $('td input[type='checkbox']').length;
    if (checkedNum == totalNum) {
      $('th input[type='checkbox']').prop('checked', true);
      allChecked = true;
    } else {
      $('th input[type='checkbox']').prop('checked', false);
      allChecked = false;
    }
  });
});
</script>

原文地址: https://www.cveoy.top/t/topic/nuHu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录