<p>$(function() {
var id = 4; // 初始化分类 ID 为 4
// 添加表标题
var h2 = $('<h2>').text('商品列表').css('text-align', 'center');
var flag = true; // 标识 h2 是否已添加
$('input[value=&quot;添加表标题&quot;]').click(function() {
if (flag) {
$(this).before(h2); // 已存在 h2,则不再添加
} else {
$(this).before(h2);
flag = true;
}
});
// 添加样式
$('input[value=&quot;添加样式&quot;]').click(function() {
$('#tab1').addClass('mc');
});
// 删除样式
$('input[value=&quot;删除样式&quot;]').click(function() {
$('#tab1').removeClass('mc');
});
// 切换样式
$('input[value=&quot;切换样式&quot;]').click(function() {
$('#tab1').toggleClass('mc');
});
// 全选复选框
$('input[type=&quot;checkbox&quot;]:first').click(function() {
$('input[type=&quot;checkbox&quot;]').prop('checked', $(this).prop('checked'));
});
// 行复选框
$('input[type=&quot;checkbox&quot;]:gt(0)').click(function() {
var allChecked = true;
$('input[type=&quot;checkbox&quot;]:gt(0)').each(function() {
if (!$(this).prop('checked')) {
allChecked = false;
return false; // 跳出 each 循环
}
});
$('input[type=&quot;checkbox&quot;]:first').prop('checked', allChecked);
});
// 添加行
$('input[value=&quot;添加&quot;]').click(function() {
var tr = $('<tr>');
tr.append($('<td>').append($('<input type="checkbox">')));
tr.append($('<td>').text(++id));
tr.append($('<td>').text($('input:first').val()));
tr.append($('<td>').text($('input:last').val()));
tr.append($('<td>').append($('<a href="#">删除</a>').click(function() {
tr.remove();
// 更新分类 ID
$('table tr:gt(1)').each(function(i) {
$(this).children('td:eq(1)').text(i + 1);
});
// 更新全选状态
$('input[type=&quot;checkbox&quot;]:first').prop('checked', false);
})));
$('#tab1').append(tr);
// 更新全选状态
$('input[type=&quot;checkbox&quot;]:first').prop('checked', false);
});
});</p>
<style>
.mc {
  border: 2px solid red;
}
</style>
<body>
<table id="tab1" border="1" width="500" align="center">
  <tr>
    <td colspan="5">分类名称:<input type="text"><br>分类描述:<input type="text" /></td>
  </tr>
  <tr>
    <td colspan="5">
      <input type="button" value="添加" />
      <input type="button" value="添加表标题" />
      <input type="button" value="添加样式" />
      <input type="button" value="删除样式" />
      <input type="button" value="切换样式" />
    </td>
  </tr>
  <tr>
    <th><input type="checkbox"></th>
    <th>分类 ID</th>
    <th>分类名称</th>
    <th>分类描述</th>
    <th>操作</th>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>1</td>
    <td>手机数码</td>
    <td>手机数码类商品</td>
    <td><a href="#">删除</a></td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>2</td>
    <td>电脑办公</td>
    <td>电脑办公类商品</td>
    <td><a href="#">删除</a></td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>3</td>
    <td>鞋靴箱包</td>
    <td>鞋靴箱包类商品</td>
    <td><a href="#">删除</a></td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>4</td>
    <td>家居饰品</td>
    <td>家居饰品类商品</td>
    <td><a href="#">删除</a></td>
  </tr>
</table>
</body>

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

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