gpt4 book ai didi

javascript - 芯片标签无法使用 Javascript 功能删除

转载 作者:行者123 更新时间:2023-12-02 21:23:55 26 4
gpt4 key购买 nike

我正在尝试创建一个以单词作为标签的输入,然后允许用户删除它们。每次单击 X 时,我都会收到错误消息

ReferenceError: remove is not defined

我不确定我做错了什么。我正在使用以下代码:

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();
}

最佳答案

看起来像是订购问题。为了安全起见,您可以使用一个对象来存储全局函数。使用 onclick 代替 href。

    function remove(i) {
items = items.filter(item => items.indexOf(item) != i);
render();
}
function render() {
list.innerHTML = '';
items.map((item, index) => {
list.innerHTML += `<li><span>${item}</span><a href="javascript: LIB.remove(${index})">X</a></li>`;
});
}

//所有函数

window.LIB = {
remove:remove,
render: render
}

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 remove(i) {
items = items.filter(item => items.indexOf(item) != i);
render();
}
function render() {
list.innerHTML = '';
items.map((item, index) => {
list.innerHTML += `<li><span>${item}</span><a href="javascript: void 0" onclick="LIB.remove(${index})">X</a></li>`;
});
}
window.LIB = {
remove:remove,
render: render
}


window.onload = function() {
render();
txt.focus();
}
<div class="ingredients">
<ul id="list"></ul>
<input type="text" id="ingredients" placeholder="type and Enter ...">
</div>

关于javascript - 芯片标签无法使用 Javascript 功能删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60786003/

26 4 0