2 回答
TA贡献1828条经验 获得超3个赞
它看起来像订购问题。为了安全起见,您可以使用对象来存储全局函数。而不是使用href 使用onclick。
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>
TA贡献1752条经验 获得超4个赞
您可以尝试将ready功能添加到您的 javascript 文件吗
$(document).ready(function(){
var txt = document.getElementById('ingredients');
var list = document.getElementById('list');
var items = ['PHP', 'React.js', 'WordPress'];
.......
});
添加回答
举报