簡體   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