简体   繁体   English

无法获取输入的值

[英]can't get the value of an input

I have a function in which I create an input like 我有一个可以在其中创建输入的函数

tr = document.createElement("tr");
td1 = document.createElement("td");
td2 = document.createElement("td");
td1.appendChild(document.createTextNode("Number:"));
td2.appendChild(document.createElement("input"));
td2.setAttribute("id", "nr");
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);

Afterward, I want to get the value of it in another function with: 之后,我想在另一个函数中获取它的值:

var nr = document.getElementById("nr").value;

it will know the nr element but the value is undefined 它会知道nr元素,但是值是undefined

As @takendarkk said, the <td> tag doesn't have a value attribute. 正如@takendarkk所说, <td>标签没有value属性。

In your code, define in a different variable the input creation so you can give it an id to referrer later, like this: 在您的代码中,在另一个变量中定义输入创建,因此您可以为它提供一个ID,以供以后引用,例如:

let tr = document.createElement("tr");
let td1 = document.createElement("td");
let td2 = document.createElement("td");
let input = document.createElement("input"); // Created input
input.setAttribute("id","nr"); // Given an id
td1.appendChild(document.createTextNode("Number:"));
td2.appendChild(input); // Appended the input element previously created
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);

As @AlexeyZelenin suggested, you should use let or var on variable definitions to prevent modifying another variable outside the current scope. 正如@AlexeyZelenin所建议的那样,您应在变量定义上使用letvar ,以防止在当前作用域之外修改另一个变量。

Look at an example: 看一个例子:

Press the button to get the value of the input. 按下按钮以获取输入值。

 const table = document.querySelector("table"); function createRow() { let tr = document.createElement("tr"); let td1 = document.createElement("td"); let td2 = document.createElement("td"); let input = document.createElement("input"); input.setAttribute("id","nr"); td1.appendChild(document.createTextNode("Number:")); td2.appendChild(input); tr.appendChild(td1); tr.appendChild(td2); table.appendChild(tr); } createRow(); function showValue(){ console.log(document.getElementById("nr").value); } 
 <table></table><button onclick="showValue()">Show value</button> 

这行设置的是<td>的ID,而不是附加的子输入元素的ID:

td2.setAttribute("id", "nr");

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

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