我正在尝试使用单词作为标签创建输入,然后允许用户删除它们。每次单击 X 时,我都会收到一条错误消息
ReferenceError:删除未定义
我不确定我做错了什么。我正在使用以下代码:
HTML:
<div class="ingredients">
<ul id="list"></ul>
<input type="text" id="ingredients" placeholder="type and Enter ...">
</div>
Javascript
var txt = document.getElementById('ingredients');
var list = document.getElementById('list');
var items = ['PHP', 'React.js', 'WordPress'];
txt.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let val = txt.value;
if (val !== '') {
if (items.indexOf(val) >= 0) {
alert('Tag name is a duplicate');
} else {
items.push(val);
render();
txt.value = '';
txt.focus();
}
} else {
alert('Please type a tag Name');
}
}
});
function render() {
list.innerHTML = '';
items.map((item, index) => {
list.innerHTML += `<li><span>${item}</span><a href="javascript: remove(${index})">X</a></li>`;
});
}
function remove(i) {
items = items.filter(item => items.indexOf(item) != i);
render();
}
window.onload = function() {
render();
txt.focus();
}
子衿沉夜
温温酱
相关分类