草庐IT

javascript - 根据 JSON 数据将元素 append 到 div

coder 2024-07-23 原文

我有一个包含“类(class)类别”和“标题”的本地 JSON 文件。每个类别有多个标题,每个标题对应一个类别。

我创建了 three separate divs :“Top Courses”、“New-Added Courses”,最后是“Top Courses”,div 按类别填充。单击类别会打开一个模式,该模式会再次显示类别名称和正确的类别描述。它应该显示与该类别关联的所有标题,例如单击“动物”类别应显示“Chinchilla”、“Axolotl”、“Flea”等。

我想做的是点击类别显示与该类别关联的标题。我在模态中看到标题---但是I'm only seeing one Title来自每个类别。根据标题的顺序,我相信它们来自“所有类(class)”类别。我不能确定是否是这种方式,但是当我点击“全部”下不是的类别时,我看到了同样的事情。

JS 片段:

var testjson = {
  "d": {
    "results": [{
      "Title": "Aardvark",
      "Category": "Animals",
      "Description": "a-desc",
      "TopTrainingCourse": false,
      "ID": 1,
      "Modified": "2019-03-05T20:13:46Z",
      "Created": "2019-03-05T20:13:36Z"
    }, {
      "Title": "Red Panda",
      "Category": "Animals",
      "Description": "a-desc",
      "TopTrainingCourse": true,
      "ID": 10,
      "Modified": "2019-03-06T21:08:25Z",
      "Created": "2019-03-06T21:08:25Z"
    }, {
      "Title": "Tennis",
      "Category": "Sports",
      "Description": "s-desc",
      "TopTrainingCourse": true,
      "ID": 11,
      "Modified": "2019-03-06T21:08:35Z",
      "Created": "2019-03-06T21:08:35Z"
    }]
  }
}


///// From topCourses.js /////

import testjson from './test.json';

export default class {
    constructor() {
    }

    loadTopCourses() {
        let topCrs = testjson.d.results
            .filter(x => x.TopTrainingCourse === true)
            .filter((el, idx, self) => { // no duplicates
                return (idx === self.map(el => el.Category).indexOf(el.Category))
            })
            .map(x => {
                return {
                    "Category": x.Category,
                    "Description": x.Description,
                    "Title": x.Title
                }
            });

        let curIndex = 0;
        $.each(topCrs, function(idx, val) {
            curIndex++; // this line must be here---if it's moved down the 1st col doesn't show
            let targetDiv = $("div.top-training-div > div[col='" + curIndex + "']");

            let modalTrigger = $('<div />', {
                'class': 'categoryName',
                'data-category': val.Category,
                'data-target': '#modal-id',
                'data-toggle': 'modal',
                'text': val.Category
            });

            targetDiv.append(modalTrigger);

            if(curIndex == 4) {
                curIndex = 0;
            }
        })

        $('.categoryName').click(function(val) {
            let cat = $(this).data('category');
            $('.modal-title').text(cat);

            // console.log($(this).data('category'));

            $(".category-desc").empty();
            var noDupeDescs = topCrs.filter(function(val) {
                return val.Category == this;
            }, cat)
            .map(function(val) {
                return val.Description;
            });

            $.each(noDupeDescs, function(idx, val) {
                $(".category-desc").append(val + "<br />")
            })

            ///

            $(".training-titles").empty();
            let titles = topCrs;



        $.each(titles, function(idx, val) { // ----- thought something like this could help
            for (var i = 0; i = titles.length; i++) {
                if $(titles.contains(val.Title)
                $(".training-titles").append("<li>" + val.Title + "</li>")
            }
        }
      });

    } // ------------------ loadTopCourses

}

模态:

<div class="modal fade" id="modal-id" role="dialog" >
     <div class="modal-backdrop">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel"></h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">CLOSE</span> <!-- &times; -->
            </button>
          </div>
          <div class="modal-body">
            <div class="category-desc"></div>
            <ul class="training-titles"></ul>
          </div>
        </div>
      </div>
     </div> <!-- modal-backdrop -->
    </div> <!-- modal fade -->

最佳答案

看起来你的错误是你迭代到 topCrs 来显示标题,但是 topCrs 是一个小数组,已经过滤并且每个类别只包含一个标题,因为你总是会看到每个类别的一个标题。

您需要做的是从 testjson.d.results 再次迭代所有标题,并按点击的类别进行过滤。

var titles = testjson.d.results.filter(x => x.Category === cat);

然后迭代这个按类别过滤的标题

$.each(titles, function(idx, val) {
    $(".training-titles").append("<li>" + val.Title + "</li>")
}

关于javascript - 根据 JSON 数据将元素 append 到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167070/

有关javascript - 根据 JSON 数据将元素 append 到 div的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  3. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  4. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  5. ruby-on-rails - Nokogiri:使用 XPath 搜索 <div> - 2

    我使用Nokogiri(Rubygem)css搜索寻找某些在我的html里面。看起来Nokogiri的css搜索不喜欢正则表达式。我想切换到Nokogiri的xpath搜索,因为这似乎支持搜索字符串中的正则表达式。如何在xpath搜索中实现下面提到的(伪)css搜索?require'rubygems'require'nokogiri'value=Nokogiri::HTML.parse(ABBlaCD3"HTML_END#my_blockisgivenmy_bl="1"#my_eqcorrespondstothisregexmy_eq="\/[0-9]+\/"#FIXMEThefoll

  6. ruby - 在哈希的键数组中追加元素 - 2

    查看我的Ruby代码:h=Hash.new([])h[0]=:word1h[1]=h[1]输出是:Hash={0=>:word1,1=>[:word2,:word3],2=>[:word2,:word3]}我希望有Hash={0=>:word1,1=>[:word2],2=>[:word3]}为什么要附加第二个哈希元素(数组)?如何将新数组元素附加到第三个哈希元素? 最佳答案 如果您提供单个值作为Hash.new的参数(例如Hash.new([]),完全相同的对象将用作每个缺失键的默认值。这就是您所拥有的,那是你不想要的。您可以改用

  7. ruby-on-rails - 如何使用 Rack 接收 JSON 对象 - 2

    我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":

  8. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  9. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

  10. FOHEART H1数据手套驱动Optitrack光学动捕双手运动(Unity3D) - 2

    本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01  客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02  数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit

随机推荐