javascript - 无法清除输入字段
问题描述
我正在用 JavaScript 创建一个过滤表。一切正常。但是,唯一似乎不起作用的行是inputValue = ''
. 不知道为什么它不想在过滤完成后清除该字段。
如果您将其替换为document.querySelector('.form__input').value
似乎可以工作的东西,但我不想重复相同的代码。我已经在上面声明为inputValue
.
const initValues = [
'Walmart',
'State Grid',
'Sinopec Group',
'China National Petrolium',
'Royal Dutch Shell',
'Toyota Motor',
'Volkswagen',
'BP',
'Exxon Mobil',
'Berkshire Hathaway'
];
const tableCreation = array => {
const tableBody = document.querySelector('.table__body');
document.querySelectorAll('tr').forEach(el => el.parentNode.removeChild(el));
array.forEach(el => {
const row = document.createElement('tr');
const cell = document.createElement('td');
const cellText = document.createTextNode(el);
cell.appendChild(cellText);
row.appendChild(cell);
tableBody.appendChild(row);
});
};
tableCreation(initValues);
const filterTable = event => {
event.preventDefault();
let inputValue = document.querySelector('.form__input').value;
const filtered = initValues.filter(el => el.toLowerCase().includes(inputValue.toLowerCase()));
if (filtered) {
inputValue ? tableCreation(filtered) : tableCreation(initValues);
}
inputValue = '';
};
document.querySelector('.form__button').addEventListener('click', filterTable);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./css/3.css">
<title>Filtered list</title>
</head>
<body>
<form class="form" id="form">
<label for="filter">Filtered: </label>
<input class="form__input" type="text" id="filter" name="input" placeholder="Insert phrase...">
<button class="form__button" form="form" type="submit">Filter</button>
</form>
<table class="table">
<tbody class="table__body"></tbody>
</table>
<script src="./js/3.js"></script>
</body>
</html>
解决方案
该变量inputValue
仅保存该字段的实际值,它与它分离。
您可以将对该字段的引用保存为变量并按如下方式清除该值:
const inp = document.querySelector('.form__input');
inp.value = '';
推荐阅读
- html - How to fix Component-Streching when using vh with flexbox?
- amazon-web-services - 通过过滤源字段上的数据,在弹性搜索 AWS 中查询分页数据的 POST 请求正文
- java - 从 RetrofitBuilder 中的 SharedPreferences 获取 BASE_URL
- matlab - 在绘图顶部绘制集群条指示器
- excel - 工作表名称更改时如何从文件夹中已关闭的工作表中复制数据?
- javascript - 如何将现有的 html 元素附加到另一个元素?
- entity-framework-core - EF 为何试图同时保存数千个实体?
- laravel - 为什么我的 laravel 安装程序版本还是 2.1.0?
- c# - 如何在 Dapper Delete Query 中使用 IN 子句作为 GUID 列表
- java - Admob 高级原生广告导致单击 A RecyclerView 中的项目时崩溃