如何使用使用Javascript动态创建的输入字段?

时间:2018-08-05 18:26:50

标签: javascript

我知道如何使用Javascript处理输入字段。但是,当我使用javascript createElement方法动态创建输入字段时,无法使用它。由于我还没有开始学习PHP,所以我想知道如何使用javascript处理动态创建的输入字段。

3 个答案:

答案 0 :(得分:0)

如果使用createElement添加元素,则可以通过按ID或类引用元素来使用该元素。

document.getElementById()

document.getElementsByClassName()

看看at MDN site为例

答案 1 :(得分:0)

跟踪(和操作)输入字段的最简单方法是使用getElementsByTagName();,它返回带有指定标签的所有元素的数组

因此,例如:

// saves all current elements in an array
var inputsArr = document.getElementsByTagName('input');
console.log('Current input fields: ' + inputsArr.length);

// now let's create our new Element and set its attributes!
var newinput = document.createElement('input');
newinput.setAttribute('type', 'button');
newinput.setAttribute('value', 'Submit form');

// adds (appends) the newly created input
document.getElementById('structure').appendChild(newinput);
console.log('-- button added');

var newinputsArr = document.getElementsByTagName('input');
console.log('Current input fields: ' + newinputsArr.length);

// and we can manipulate with the newly added element
newinputsArr[2].setAttribute('style', 'background:gold;');
input[type="button"]{
  display: block;
  margin-top: 10px;
}

#structure {
  background: lightgray;
  height: 70px;
}
<form id="structure">
Login: <input type="text">
Password: <input type="password">
</form>

在下面展示的摘录中

  1. 如何使用现有输入元素填充数组
  2. 如何添加新的输入项然后访问它
  3. 如何使用新添加的元素

注意,我有意创建了两个单独的数组作为展示。因此,如果您打算操纵例如。仅包含新添加的元素,您可以将表达式仅应用于newinputsArr.lengthinputsArr.length之间的'extra'元素

答案 2 :(得分:0)

您可能忘记了将输入字段添加到文档正文中。当您使用document.createElement创建元素时,切勿忘记在完成后将其附加到正文。

var input = document.createElement("input");
document.body.appendChild(input);

<span id="result"></span><br/>
<script>
var input = document.createElement("input");
input["type"] = "text";
document.body.appendChild(input);
input.addEventListener("keypress", function(e){
  document.getElementById('result').textContent = "Key: "+e.key+" KeyCode: "+e.keyCode+" Value: "+this.value+e.key;
});
</script>