JavaScript AppendChild问题

时间:2019-04-02 03:30:06

标签: javascript html arrays javascript-objects

已更新完整代码

我正在尝试将div动态添加到存储在数组中的其他DIV上

包含DIV的数组被命名为categoryData,其中包含一个属性为category name

shop-row div的(categoryData)开头为空。

我还有另一个数组,其中包含存储在名为的数组中的产品对象 storeCategoryData 产品对象采用以下格式,

{CategoryName:categoryname,StoreObject:store_clearfix} // store_clearfix is another div

我正在尝试将StoreObject添加到DIV categoryData中。 不幸的是,添加了一些对象,而没有添加其他对象。我可以弄清楚我在做什么错。任何帮助将非常感激。 谢谢!

我尝试了一切可能。还是没有运气:(

 var store_list = document.getElementsByClassName("shop-list")[0];


if(data['stores']!=null && data['stores'] !== typeof undefined){

    var numstores = Object.keys(data["stores"]).length;
    var count = 0;

    while (count < numstores) {

        var categories = data["stores"][count].Categories;
        var catcount = categories.length;
        var c=0;

        while(c<catcount){
            var cat = categories[c];

            if (!(storeCategories.indexOf(cat) > -1)) {

                var category_element = document.createElement("li");
                if(count==0 && c==0){
                    category_element.className="active";
                }
                var clickable = document.createElement("a");
                clickable.href = "#";
                clickable.innerText = cat;
                clickable.setAttribute("category-data", cat);
                storeCategories.push(cat);
                category_element.appendChild(clickable);
                category_list.appendChild(category_element);


                var div = document.createElement("div");
                div.className = "shop-row";
                div.setAttribute("category-name", cat);
                categoryData.push(div);
            }

            c++;
        }

        count++;
    }

    count = 0;

    while (count < numstores) {

        var StoreId = data["stores"][count].StoreId;
        var WebsiteUrl = data["stores"][count].WebsiteUrl;
        var LogoUrl = data["stores"][count].LogoUrl;
        var categories = data["stores"][count].Categories;


        var store_clearfix = document.createElement("div");
        store_clearfix.className = "single-products-catagory clearfix";

        var store_atag =  document.createElement("a");
        store_atag.className = "home-shop";
        store_atag.href = WebsiteUrl;

        var store_img = document.createElement("img");
        store_img.className = "shop-icon";
        store_img.src = LogoUrl;
        store_img.alt = StoreId;

        store_atag.appendChild(store_img);
        store_clearfix.appendChild(store_atag);


        c=0;
        catcount = categories.length;
        while(c<catcount){
            var categoryname = categories[c];
            var i = 0;
            var datacount = categoryData.length;
            while(i<datacount){

                var datarow = categoryData[i];
                if(categoryname==datarow.getAttribute("category-name")) {
                    var storeObj = {CategoryName:categoryname,StoreObject:store_clearfix};
                    storeCategoryData.push(storeObj);
                    break;
                }

                i++;

            }

            c++;
        }


        count++;

    }


    categories_tab.appendChild(category_list);

    i=0;
    for (i = 0; i < categoryData.length; i++) {
        var div = categoryData[i];
        console.log(div);

        var name = div.getAttribute("category-name");

        var c;
        for (c = 0; c < storeCategoryData.length; c++) {
            console.log(storeCategoryData[c].CategoryName);
            if(storeCategoryData[c].CategoryName==name){
                console.log(storeCategoryData[c].StoreObject);
                div.appendChild(storeCategoryData[c].StoreObject);
           }

        }

        console.log("Finished "+name );
        console.log(div);
        store_list.appendChild(div);

    }

}

变量data的定义如下

{
"status": "success",
"stores": [
    {
        "StoreId": "randomStore",
        "WebsiteUrl": "https://abcd.com",
        "LogoUrl": "https://abcd.come",
        "Categories": [
            "ALL",
            "MENS",
            "WOMENS"
        ]
    },
    {
        "StoreId": "someStoreId",
        "WebsiteUrl": "https://someurl.com",
        "LogoUrl": "https://someLogo.com",
        "Categories": [
            "MENS"
        ]
    }
  ] 
}

enter image description here

3 个答案:

答案 0 :(得分:1)

您在此处面临的问题是由以下行为引起的:

  

Node.appendChild()方法将节点添加到列表的末尾   指定父节点的子节点。如果给定的孩子是参考   到文档中的现有节点,appendChild()将其从文档中移到   当前位置到新位置(MDN: Node.appendChild()

这意味着 appendChild 将删除该节点(如果该节点已经存在于DOM中),这就是我们在此处看到的。可以通过先使用 cloneNode 创建节点的深克隆,然后再将其附加到目标div来轻松解决此问题,如下所示:

var clone = storeCategoryData[c].StoreObject.cloneNode(true);
div.appendChild(clone);

您也可以参考下面的代码片段作为工作示例:

var categories_tab = document.getElementById('category-tab');
var store_list = document.getElementById('store-list');
var storeCategories = [];
var storeCategoryData = [];
var data = {
  "status": "success",
  "stores": [{
      "StoreId": "randomStore",
      "WebsiteUrl": "https://abcd.com",
      "LogoUrl": "https://abcd.come",
      "Categories": [
        "ALL",
        "MENS",
        "WOMENS"
      ]
    },
    {
      "StoreId": "someStoreId",
      "WebsiteUrl": "https://someurl.com",
      "LogoUrl": "https://someLogo.com",
      "Categories": [
        "MENS"
      ]
    }
  ]
};

var categoryData = [];

var category_list = document.createElement("ul");

if (data['stores'] != null && data['stores'] !== typeof undefined) {

  var numstores = Object.keys(data["stores"]).length;
  var count = 0;

  while (count < numstores) {

    var categories = data["stores"][count].Categories;
    var catcount = categories.length;
    var c = 0;

    while (c < catcount) {
      var cat = categories[c];

      if (!(storeCategories.indexOf(cat) > -1)) {

        var category_element = document.createElement("li");
        if (count == 0 && c == 0) {
          category_element.className = "active";
        }
        var clickable = document.createElement("a");
        clickable.href = "#";
        clickable.innerText = cat;
        clickable.setAttribute("category-data", cat);
        storeCategories.push(cat);
        category_element.appendChild(clickable);
        category_list.appendChild(category_element);


        var div = document.createElement("div");
        div.className = "shop-row";
        div.setAttribute("category-name", cat);
        categoryData.push(div);
      }

      c++;
    }

    count++;
  }

  count = 0;

  while (count < numstores) {

    var StoreId = data["stores"][count].StoreId;
    var WebsiteUrl = data["stores"][count].WebsiteUrl;
    var LogoUrl = data["stores"][count].LogoUrl;
    var categories = data["stores"][count].Categories;


    var store_clearfix = document.createElement("div");
    store_clearfix.className = "single-products-catagory clearfix";

    var store_atag = document.createElement("a");
    store_atag.className = "home-shop";
    store_atag.href = WebsiteUrl;

    var p = document.createElement("p");
    p.className = "shop-icon";
    var t = document.createTextNode(LogoUrl);
    p.appendChild(t)

    store_atag.appendChild(p);
    store_clearfix.appendChild(store_atag);


    c = 0;
    catcount = categories.length;
    while (c < catcount) {
      var categoryname = categories[c];
      var i = 0;
      var datacount = categoryData.length;
      while (i < datacount) {

        var datarow = categoryData[i];
        if (categoryname == datarow.getAttribute("category-name")) {
          var storeObj = {
            CategoryName: categoryname,
            StoreObject: store_clearfix
          };
          storeCategoryData.push(storeObj);
          break;
        }

        i++;

      }

      c++;
    }


    count++;

  }


  categories_tab.appendChild(category_list);

  i = 0;
  for (i = 0; i < categoryData.length; i++) {
    var div = categoryData[i];
    console.log(div);

    var name = div.getAttribute("category-name");

    var c;
    for (c = 0; c < storeCategoryData.length; c++) {
      console.log(storeCategoryData[c].CategoryName);
      if (storeCategoryData[c].CategoryName == name) {
        console.log(storeCategoryData[c].StoreObject);
        var clone = storeCategoryData[c].StoreObject.cloneNode(true);
        div.appendChild(clone);
      }

    }

    console.log("Finished " + name);
    console.log(div);
    store_list.appendChild(div);

  }

}
<div id="category-tab" style="min-height: 20px; border: 1px solid; padding: 10px"></div>
<div id="store-list" style="min-height: 20px; border: 1px solid green; padding: 10px; margin-top: 30px"></div>

答案 1 :(得分:0)

我无法完全理解您在此处写的内容,但是正如我看到的那样,您想从JSON字符串而不是Node附加appendChild。

var div = categoryData[i];

应该是这样的:

store_list.innerHTML += DIV;

我什至不会用NULL或空数组categoryData开始while循环。我会将其外包给一个函数,因为如果我想再次动态调用它,或者首先查看它是否可用。 storeCategoryData是一个对象,而不是数组...等等

答案 2 :(得分:-1)

我认为原因是一个商店元素只能追加到一个类别元素,即使它可能属于多个类别。

=========保持以下历史记录:===================

日志对我来说似乎很完美。我看不到问题。

您写了以下声明:

if(storeCategoryData[c].CategoryName==name)

因此,附加了一些StoreObject;其他不是。