[英]How do I create a input field dynamically in js
如何使用 javascript 創建輸入字段,當我運行它時,它不會創建輸入。
我正在嘗試刪除兩個輸入字段,然后再創建兩個帶有 id 的字段並將它們設置為鍵入文本。
這段代碼一直有效,直到它到達創建元素,除了 body.appendchild 不是 function,我沒有收到任何錯誤,我很困惑。
var securityCode1;
var securityCode2;
var securityCode3;
function signUp() {
var securityCode = document.getElementById('securityCode').value;
var password = document.getElementById('password').value;
var code = [];
var passwordArry = [];
code = securityCode.slice();
console.log(securityCode[5]);
var num1 = Math.floor(Math.random() * securityCode.length +1 );
var num2 = Math.floor(Math.random() * securityCode.length + 1);
var num3 = Math.floor(Math.random() * securityCode.length + 1);`
securityCode1 = securityCode[num1];
securityCode2 = securityCode[num2];
securityCode3 = securityCode[num3];
create();
}
function create() {
securityCode.remove();
password.remove();
var button = document.getElementsByTagName("button")[0].removeAttribute('id');
securityCodeE = document.createElement('input');
securityCodeE.type = "text";
securityCodeE.setAttribute('id', 'secuirtyCodeE');
var body = document.getElementsByTagName('body');
body.appendChild(securityCodeE);
var passwordE = document.createElement('INPUT');
passwordE.setAttribute('id', 'passwordE');
}
GetElementsByTagName
將返回一個元素數組,因此您需要訪問第一個元素:
var body = document.getElementsByTagName('body')[0];
// appendChild will now work for you
body.appendChild(securityCodeE);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.