![](/img/trans.png)
[英]How to dynamically remove input field which is created dynamically using JavaScript
[英]How to work with input field that is created dynamically using Javascript?
我知道如何使用Javascript處理輸入字段。 但是,當我使用javascript createElement方法動態創建輸入字段時,無法使用它。 由於尚未開始學習PHP,因此我想知道如何使用javascript處理動態創建的輸入字段。
跟蹤(和操作)輸入字段的最簡單方法是使用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>
在下面的代碼段中,我展示了
注意,我有意創建了兩個單獨的數組作為展示。 因此,如果您打算操縱例如。 僅使用新添加的元素,您可以將表達式僅應用於newinputsArr.length
和inputsArr.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.