我有一个 HTML 表格,我想做的是找到其中的第二列并将其值放入字符串数组中。
稍后我想做简单的 if 检查,看看我在一个文本框中输入的值是否已存在于该数组中。但是当我尝试获取文本框的 .innerHTML 或数组元素的 .innerHTML 时,我总是收到“未定义”的消息。我也尝试过 .value 和 .innerText,但得到了相同的结果。
我只能使用纯 JavaScript,所以不能使用 jQuery 或其他库。我在这里缺少什么?
这是我的表格 HTML:
<table id="results" width="360" border="1">
<thead>
<tr>
<th scope="col" width="120">Date Created</th>
<th scope="col" width="120">Name</th>
<th scope="col" width="120">Tests</th>
</tr>
</thead>
<tbody>
<tr/>
<td>07/08/2015</td>
<td>Test Name</td>
<td>Raven</td>
</tr>
<tr/>
<td>01/08/2017</td>
<td>Test Name 2</td>
<td>PCT</td>
</tr>
</tbody>
</table>
这是文本框的 HTML:
<form name="formTestInfo" method="post">
Name:<br>
<input type="text" id="tbName" name="tbName">
<p id="nameVal"></p>
</form>
这是我的脚本代码:
var secondCell = document.querySelectorAll('td:nth-child(2)');
var cellValues = [];
secondCell.forEach(function(singleCell) {
cellValues.push(singleCell.innerText);
});
for(var i=0; i < cellValues.length ; i++)
{
if(document.getElementById("nameVal").innerHTML == cellValues[i].innerHTML)
{
var nameVal = "Name already exists in table!";
validation = false;
}
}
我永远不会进入 if 因为永远找不到值,但数组填充了正确的值。有人看出这里出了什么问题吗?
最佳答案
试试这个:
var secondCell = document.querySelectorAll('td:nth-child(2)');
var cellValues = [];
secondCell.forEach(function(singleCell) {
cellValues.push(singleCell.innerText);
});
for(var i=0; i < cellValues.length ; i++)
{
if(document.getElementById("tbName").value == cellValues[i])
{
var nameVal = "Name already exists in table!";
validation = false;
}
}
关于javascript - 在 javaScript 中,innerHTML 始终返回 'undefine',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38891283/