简体   繁体   English

如何将 div 链接到 JavaScript 生成的 HTML 中的一个容器?

[英]How to link divs to one container within JavaScript generated HTML?

I'm a JavaScript beginner and right now I'm trying to generate HTML with JavaScript.我是 JavaScript 初学者,现在我正在尝试使用 JavaScript 生成 HTML。 I'm able to code constructors for the container and div but having troubles to link the divs with one container.我能够为容器和 div 编写构造函数,但是在将 div 与一个容器链接时遇到了麻烦。 I know that there is something like appendChild but I can't get it to work in a object orientated fashion.我知道有类似 appendChild 的东西,但我无法让它以面向对象的方式工作。 Here is what I'm working on:这是我正在做的事情:

    const body = document.querySelector("body");
    const div = document.querySelector("div");
    
    
    function Container () {
        container = document.createElement("div");
        body.appendChild(container);
        container.classList.add("cardContainer");
    }

    function Card () {

    let card = document.createElement("div");
    card.classList.add("card");
    container.appendChild("card");

    let cardPic = document.createElement("div");
    card.appendChild(cardPic);
    cardPic.classList.add("picture");

    let cardTitle = document.createElement("div");
    card.appendChild(cardTitle);
    cardTitle.classList.add("title");

    let cardDesc = document.createElement("div");
    card.appendChild(cardDesc);
    cardDesc.classList.add("desc");
}

    

With this I want to have ONE container and create many cards which sit in that container.有了这个,我想拥有一个容器并创建许多位于该容器中的卡片。 I'm using a constructor to have the possibility to generate individual cards later.我正在使用构造函数来稍后生成单张卡片。

Many thanks, canny非常感谢,精明的

I would rather use new class syntax.我宁愿使用新的类语法。

class Container {
  constructor() {
    this.container = document.createElement("div");
    body.appendChild(container);
    container.classList.add("cardContainer");
  }

  addChild(node) {
    this.container.appendChild(node)
  }
}

// usage
const container = new Container()
container.addChild(card)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM