我正在 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 = '';
关于javascript - 无法清除输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56074210/