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

如何在jQuery中根据帖子ID筛选对应评论?

解决评论按帖子ID筛选展示的问题

原代码存在的核心问题

  • 变量作用域问题:postId定义在第一个AJAX的success回调内部,后续获取评论的请求无法访问该变量,导致筛选条件失效。
  • 筛选条件错误:评论关联帖子的字段是postId,原代码错误使用了评论自身的id进行匹配。
  • 冗余循环操作:在forEach循环内重复调用filter遍历所有评论,造成不必要的性能损耗。
  • HTML拼写错误:caard-header、caard-body应为card-header、card-body,导致样式失效。

修正后的代码

$(function () {
  // 先获取URL中的postId,提升作用域
  var params = new window.URLSearchParams(window.location.search);
  var postId = params.get('post');

  if (!postId) {
    alert('请指定帖子ID');
    return;
  }

  // 请求帖子详情
  $.ajax({
    type: "GET",
    url: "https://jsonplaceholder.typicode.com/posts",
    dataType: 'json',
    success: function (result) {
      var postObj = result.filter(function (postElm) {
        return postId == postElm.id;
      });
      if (postObj.length < 1) {
        alert('post not found');
        return;
      }
      renderPage(postObj[0]);
      // 获取并筛选对应帖子的评论
      loadComments(postId);
    }
  });

  function renderPage(post) {
    $("#loop").append(
      "<div class='card bg-success text-white'>User ID:" + post.userId +
      "<div class='card-header'>ID:" + post.id + "</div>" +
      "<div class='card-body'>" +
      "<a data-post='" + post.id + "'><h5 class='card-title'>" + post.title + "</h5></a>" +
      "<p class='card-text'>" + post.body + "</p></div></div>"
    );
  }

  function loadComments(targetPostId) {
    $.getJSON('https://jsonplaceholder.typicode.com/comments', function (data) {
      // 先筛选出当前帖子的评论
      var filteredComments = data.filter(function (comElm) {
        return comElm.postId == targetPostId;
      });
      // 遍历渲染筛选后的评论
      filteredComments.forEach(comment => {
        $("#comm").append(
          `<div class='card bg-secondary text-white mb-2'>
            <div class='card-header'>postId: ${comment.postId} | ID: ${comment.id}</div>
            <div class='card-body'>
              <h6 class='card-title'>Name: ${comment.name}</h6>
              <p class='email'>Email: ${comment.email}</p>
              <p class='form-control comment-text text-white'>Body: ${comment.body}</p>
            </div>
          </div>`
        );
      });
    });
  }
});

关键修改说明

  1. 提升变量作用域:把postId的获取放在最外层,确保后续请求能访问到该值。
  2. 修正筛选条件:使用comElm.postId == targetPostId匹配评论所属的帖子ID。
  3. 优化渲染逻辑:先筛选评论再遍历渲染,避免重复遍历数据。
  4. 修复HTML错误:修正卡片类名的拼写错误,同时优化了卡片结构的可读性。
  5. 拆分功能函数:把评论加载逻辑拆分为独立函数loadComments,代码更清晰易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:13:22