Javascript AppendChild 问题

标签 javascript html arrays javascript-objects

更新了完整代码

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

包含 DIV 的数组被命名为 categoryData,它包含一个属性及其 类别名称

商店行的 div (categoryData) 开头是空的。

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

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

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

我尽了一切可能。仍然没有运气:(

 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

最佳答案

您在这里遇到的问题是由以下行为引起的:

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (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>

关于Javascript AppendChild 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55466571/

相关文章:

javascript - React-Native-snap-carousel 检查条件与状态值?

javascript - ionic : How to make Angular Translate js working with Search Filter when language changed?

html - Internet Explorer 不呈现从 JQuery ajax post 返回的 html

CSS 背景附件不起作用,无法修复背景上的填充/边距

c++ - 关于数组指针的问题?

arrays - VBA如何在消息框中显示数组

asp.net - 监听事件: in HTML from . NET

javascript命名空间问题jsfiddle

javascript - 带有 Typescript 和 react-redux 的有状态组件 : Argument of type 'typeof MyClass' is not assignable to parameter of type Component

javascript - 如何在 Bootstrap4 中为切换导航在一行中显示多个列表链接?