WordPress中jQuery实现选中复选框生成排序对象数组并去重渲染
解决方案
核心思路
- 用全局数组维护选中条目,以
data-id作为唯一标识实现去重 - 复选框状态变更时,更新数组(添加/移除条目)
- 对数组按
state字段排序分组,确保同状态条目聚合 - 根据排序后的数组重新渲染模态框内容
完整代码实现
// 全局数组存储选中条目,格式:[{item: DOM元素, state: 状态文本, id: 唯一标识}, ...] let selectedItems = []; // 定义state的排序优先级(可根据需求调整顺序) const stateOrder = ['state one', 'state two', 'state three']; const $modal = $('.modal'); // 用事件委托兼容AJAX动态生成的条目 $(document).on('change', '.add-to-modal', function() { const $item = $(this).closest('.item'); const itemId = $item.data('id'); const itemState = $item.find('.state').text().trim(); if (this.checked) { // 去重:检查当前条目是否已在数组中 const isDuplicate = selectedItems.some(item => item.id === itemId); if (!isDuplicate) { // 添加新条目到数组 selectedItems.push({ id: itemId, state: itemState, item: $item.clone() }); // 按state排序分组 selectedItems.sort((a, b) => { return stateOrder.indexOf(a.state) - stateOrder.indexOf(b.state); }); } } else { // 取消选中时移除对应条目 selectedItems = selectedItems.filter(item => item.id !== itemId); } // 渲染模态框内容 renderModal(); }); // 模态框渲染函数 function renderModal() { $modal.empty(); selectedItems.forEach(entry => { $modal.append(entry.item); }); }
代码说明
- 去重逻辑:通过
some()方法检查数组中是否存在相同id的条目,避免重复添加 - 排序逻辑:利用预定义的
stateOrder数组,通过indexOf()获取状态的优先级索引,实现按指定顺序分组排序,新增同状态条目会自动插入对应分组位置 - 动态兼容:使用事件委托绑定
change事件,适配AJAX搜索动态生成的新条目 - DOM同步:每次复选框状态变更后,清空模态框并重新渲染排序后的条目,确保展示内容与数组完全同步
自定义调整
如果后续state的可选值或排序顺序需要修改,只需调整stateOrder数组的内容即可,比如要让state three排在最前,修改为:
const stateOrder = ['state three', 'state one', 'state two'];
内容的提问来源于stack exchange,提问作者Alipvd
相关产品推荐
相关产品推荐

