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

使用jQuery detach()实现博客分类筛选仅保留选中分类的问题咨询

解决方案

问题根源

你现有代码逻辑完全反了:else分支中调用$(dataFilter).detach()是把匹配选中分类的文章直接从DOM里移除,自然就剩下了非选中分类的内容。

修正方案(基于现有detach逻辑,保留原有排序规则)

你不需要额外加自定义标识,直接用jQuery的:not()选择器筛选出非选中分类的文章做detach即可,修正后的JS代码如下:

var divs;
    
$('.blog-article').each(function(i){
  $(this).data('initial-index', i);
});

document.querySelectorAll('.blog-filter_item').forEach(el => {
  el.addEventListener('click', () => {
    document
      .querySelector('.blog-filter_item.active')
      .classList.remove('active');
    el.classList.add('active');

    const dataFilter = $(el).attr('data-filter');

    // 先把上一次筛选移除的文章全部插回原位置,恢复完整列表
    if (divs) {
      $(divs).appendTo('.blog-list').each(function(){
        const oldIndex = $(this).data('initial-index');
        $('.blog-article').eq(oldIndex).before(this);
      });
      divs = null;
    }

    if (dataFilter == 'all') {
      // 全部分类就直接显示所有文章
      $('.blog-article').show();
    } else {
      // 核心修改:筛选出【不匹配当前选中分类】的文章 detach 移除,保留选中分类的文章
      divs = $(`.blog-article:not(${dataFilter})`).detach();
    }
  });
});

更轻量的替代方案(无需操作DOM增删)

如果没有特殊要求必须移除非选中文章的DOM节点,直接用显示隐藏逻辑更简单,性能也相当,代码可以简化很多:

$('.blog-filter_item').on('click', function() {
  // 切换激活状态
  $('.blog-filter_item.active').removeClass('active');
  $(this).addClass('active');
  
  const filter = $(this).data('filter');
  if (filter === 'all') {
    $('.blog-article').show();
  } else {
    $('.blog-article').hide();
    $(filter).show();
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:24:02