根据数据中存在多少元素动态生成div

时间:2019-04-22 15:28:26

标签: javascript jquery axios fetch element

在后端,我有七个类别,我想动态创建div来容纳每个类别。数据是通过axios获取的,我可以通过其url看到数据。

JS代码段:

import $ from 'jquery';
import axios from 'axios';

let _library,
    _categories;

export default class {
    constructor() {
        this.callRESTAPI();
    }

    callRESTAPI(){
        axios.all([
            axios.get([redacted].siteAbsoluteUrl + "/[redacted]/_api/web/lists/getByTitle('Categories')/items?$select=Title,Description&$orderby=Title&$top=1000", {
                method: "GET",
                credentials: "include",
                mode: "no-cors",
                headers: {
                    "Accept": "application/json; odata=verbose"
                }
            }),

    /// irrelevant code ///

    ]).then(axios.spread((cat, lib, admn) => {
            _categories = cat.data.d.results;
            _library = lib.data.d.results;

            this.loadCourses();
        })).catch(error => {
            console.log(error);
        });
    }

    getCategories(){
        return _categories;
    }

    loadCourses() {
        let crs = _library
            .map(x => {
                return x.Category.Title;
            }).sort();

        this.populateCategory(crs, "div.top-training");

        let htmlElems = "";
        for (var i = 0; i < crs.length; i++) {
            htmlElems += "<div class='box'></div>";
        }

        let container = document.getElementById("container");
        container.innerHTML = htmlElems;

    }

HTML片段:

<div class="top-training"></div>

数据段:

<feed xmlns="">
<id></id>
<content type="application/xml">
<m:properties>
 <d:Title>Animals</d:Title>
 <d:Description>
   Animals are multicellular...
 </d:Description>
</m:properties>
</content>
</entry>

0 个答案:

没有答案