繁体   English   中英

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

[英]How to work with input field that is created dynamically using Javascript?

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

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

document.getElementById()

document.getElementsByClassName()

看看MDN网站上的示例

跟踪(和操作)输入字段的最简单方法是使用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之间差异的“额外”元素

您可能忘记了将输入字段添加到文档正文中。 使用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> 

暂无
暂无

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

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