【问题标题】:Create input labels from "for" attribute, without changing HTML从“for”属性创建输入标签,而不更改 HTML
【发布时间】:2017-09-28 09:41:36
【问题描述】:

在大学课程中学习 JavaScript 时遇到问题。这是我的最后一个项目,我在 HTML 代码中遇到的问题是为没有 id 的标签创建一个输入字段,但它有一个“for”元素。它不能用 JQuery 或 JSON 创建。

所以 HTML 看起来像这样: 你有什么车?

所以我想我可以创建输入文本字段并将其添加到 DOM:

// Create the input field
var firstCar = document.createElement("input");
// Create the type node and store what the field will be text
var newType = document.createTypeNode("text");
// Create a new ID of car and attach it to the input
var newID = document.createIdNode("car")
/* put the created Element within the HTML with ["this determines which label it will be under"]:*/
var position = document.getElementByTagName("label")[1];
// Insert the element into the position
position.appendChild(firstCar);

我运行了它,它说 TypeNode 在我的浏览器中不是一个函数。

【问题讨论】:

  • 仅供参考 - 当 input 元素未指定 type 属性时,它默认为 <input type='text'>
  • 我们的网页已更改,不再需要。但是,如果有人仍然想回答这个问题,我会很感激了解更多关于 DOM 操作的信息。谢谢马库斯。
  • getElementsByTagName,注意Elements的复数形式。

标签: javascript html for-loop dom


【解决方案1】:

这不是您设置typeid 的方式。试试这个

var firstCar = document.createElement("input");

firstCar.type = "text"; // set the type

firstCar.id = "car";    // set the ID

var position = document.getElementsByTagName("label")[1]; // it should be getElements... not getElement...

position.appendChild(firstCar);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2018-09-20
    • 1970-01-01
    • 2015-12-15
    相关资源
    最近更新 更多