【问题标题】:Javascript Create an element with the various attributesJavascript 创建具有各种属性的元素
【发布时间】:2013-07-27 03:41:43
【问题描述】:

你能创建一个元素而不是每次都这样吗?

var button = document.createElement('button');
button.class = codebuttons;
button.value = Backup

例如

document.querySelector('.right.Sub').appendChild(document.createElement("button").setAttribute("class", "codebuttons"));

【问题讨论】:

  • 您自己提出问题并回答它......我们还剩下什么......

标签: javascript class createelement


【解决方案1】:

您的“示例”代码与上面的代码非常不同,但都需要修复。

首先是您的初始代码。除了您需要使用.className 来设置类之外,这将起作用。当然,您需要引号来创建字符串。

var button = document.createElement('button');
button.className = "codebuttons";
button.value = "Backup";

其次,您的底部代码将不起作用,因为您没有附加元素。您正在附加.setAttribute() 的返回结果,即undefined

但是,您可以将 .setAttribute() 链接到 .appendChild() 的末尾,因为它返回附加的元素。

document.querySelector('.right.Sub')
        .appendChild(document.createElement("button"))
        .setAttribute("class", "codebuttons");

然而,在旧版本的 IE 中使用setAttribute() 设置"class" 存在问题。因此,请按照第一个示例设置属性。

document.querySelector('.right.Sub')
        .appendChild(document.createElement("button"))
        .className = "codebuttons";

【讨论】:

  • 有了这段代码,我只有类型,没有价值。 document.querySelector('.right.Sub') .appendChild(document.createElement("input")) .setAttribute("type", "button") .setAttribute("value", "Backup");
  • 当然,如果您需要设置多个属性/属性,那么您应该将新元素保存到变量中并设置它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多