简体   繁体   English

如何使用给定的标签名称创建一个 ES6 class 来创建新的 HTML 元素并具有操作它的方法?

[英]How can I create an ES6 class that creates new HTML elements using given tag name and has methods to manipulate it?

I am trying to create a class in ES6 that would create new HTML items with a given tag name.我正在尝试在 ES6 中创建一个 class ,它将创建具有给定标签名称的新 HTML 项目。 In it would be methods to append it or change innerHTML.其中将是 append 的方法或更改 innerHTML。

My questions:我的问题:
1) how to pass into the document.createElement a new tag name, because literal ${} is not working as I would expect 1)如何将一个新的标签名称传递给 document.createElement,因为文字${}没有像我预期的那样工作
2) where to transform "this" - newly created "HTMLElement" into HTML element (createElement). 2)将“this”转换为新创建的“HTMLElement”到 HTML 元素(createElement)的位置。 I have a feeling it should not be in a constructor, but I don't know where to place it, do the class would transform it upon creating.我有一种感觉它不应该在构造函数中,但我不知道在哪里放置它,class 会在创建时对其进行转换。

class HTMLElement {
  constructor (tagName){
    this.tagName = document.createElement(`${tagName}`);
  }

  addText(text) {
    this.innerHTML = text;
  }

  appendItem(parent) {
    let appendTo = document.getElementsByTagName(`${parent}`);
    appendTo.appendChild(this);
  }
}

you are probably thinking of it too generically, different type of events can have different parameters, so you should think about that and based on the tag names you should set the properties.你可能想得太笼统了,不同类型的事件可以有不同的参数,所以你应该考虑一下,并根据标签名称设置属性。 for example if you wanna create button it will have a name , which is not required for a span or div or if you wanna create a input element you may need to set some default value .例如,如果您想创建按钮,它将有一个名称,这对于spandiv不是必需的,或者如果您想创建一个输入元素,您可能需要设置一些默认

To handle this, you can either handle tags individually or group similar elements( tags ) with common properties .要处理这个问题,您可以单独处理标签,也可以将具有共同属性的相似元素(标签分组

Answering your point,回答你的观点,

1.) you can directly pass the value 1.)您可以直接传递值

this.tagName = document.createElement(tagName);

2.) "this" here is an object, and the element you have created is stored on this.tagName 2.) 这里的“this”是一个object,你创建的元素存储在this.tagName

appendItem(parent) {
    let appendTo = document.getElementsByTagName(parent);
    appendTo.appendChild(this.TagName);
  }

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

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