我正在用Vanilla Javascript编写待办事项列表,我希望每次有人在上一个返回值上按回车键时,它都可以创建一个新的输入,此输入现在可以使用。我还想在其上附加一个选中标记,因此,每当任务完成时,您都可以单击它,它将更改选中标记旁边的输入的背景色。唯一的问题是,我不知道如何为每个检查标记分配某种值,因此eventListener并不总是获得选择的第一个ID。
试图为每个选中标记分配一个值,然后将其放入数组中,但是不知道如何将每个选中标记完全相同的值分配给数组。
let counter, checkmark, cross, list, newRow, addInput, addCheckmark, listid, wrapper, current1;
counter = 1;
checkmark = document.getElementById('checkmark');
cross = document.getElementById('cross');
wrapper = document.querySelector('.to-do-wrapper');
current1 = document.getElementById('current1');
let values = [];
// Event Delegation to listen to all target.matches :)
document.addEventListener('keypress', function(e) {
if (event.target.matches('.input-new-list')) {
let randomVal = Math.floor(Math.random() * 100000);
list = document.querySelector('.list');
newRow = document.createElement("li");
addInput = document.createElement('input');
addCheckmark = document.createElement('i');
addCheckmark.setAttribute('class', 'fas fa-check');
addInput.setAttribute('id', 'current-' + counter)
addInput.setAttribute('class', 'input-new-list');
addInput.setAttribute('type', 'text');
newRow.setAttribute('class', 'new-list');
let key = e.keyCode;
if (key === 13) {
list.appendChild(newRow);
newRow.appendChild(addCheckmark);
addCheckmark.setAttribute('id', 'checkmark');
/* addCheckmark.setAttribute('value', randomVal);
values.push(randomVal); */
newRow.appendChild(addInput);
document.getElementById('current-' + counter).focus();
counter++;
document.querySelector('#default').removeAttribute('placeholder');
}
}
});
// Show edit buttons on click edit list
document.addEventListener('click', function(event) {
list = document.querySelector('.list');
newRow = document.createElement("li");
addInput = document.createElement('input');
addCheckmark = document.createElement('i');
// Ad a random value to checkmark -> Push into array. If event.target.matches checkmark value => execute if
if (event.target.matches('#checkmark')) {
// On click of checkmark, change input background and toggle checkmark color
if (event.target.classList !== 'active') {
checkmark.classList.toggle('active');
if (document.querySelector('.input-new-list')) {
document.querySelector('.input-new-list').classList.toggle('checked');
} else if (document.querySelector('current' + counter)) {
document.querySelector('#current' + counter).classList.toggle('checked')
}
}
}
});
document.addEventListener('mouseover', function() {
if (event.target.matches('input')) {
cross.classList.add('active');
} else if (!event.target.matches('input')) {
cross.classList.remove('active');
}
});
<div class="container-fluid to-do-wrapper" id="toDo">
<ul class="list">
<li class="new-list">
<i class="fas fa-check" id="checkmark"></i>
<input type="text" placeholder="Create a new list" class="input-new-list" id="default" />
<i class="fas fa-times" id="cross"></i>
</li>
</ul>
</div>
只需寻找一种将每个选中标记和输入分配给其父li
的方法,这样对它进行某些操作就不会影响第一个选定元素,而是会对其进行编辑。
答案 0 :(得分:1)
您可以通过添加/删除类来“分配值”以选中标记。不要对许多元素使用相同的id
。尝试使用<template>
作为follows
let list= [{text:'', done: false}]; // data
function show() {
toDo.innerHTML = list.map((x,i)=> inject(item.innerHTML,{
check: x.done ? 'fa-check' : 'fa-uncheck',
done: x.done ? 'done' : '',
hide: i ? '' : 'hide',
text: x.text,
i,
})).join('');
}
function inject(str, obj) { return str.replace(/\${(.*?)}/g, (x,g)=> obj[g]) }
function check(i) { list[i].done = !list[i].done; show(); }
function change(inp,i) { list[i].text = inp.value; }
function del(i) { list.splice(i,1); show(); }
function newItem(i) {
list.splice(i+1,0,{text:'',done: false});
show();
this['inp'+(i+1)].focus();
}
show();
ul{ list-style-type: none; }
.fas { cursor: pointer }
.done { background: #dfd }
.input-new-list {margin: 5px}
.fa-check::after { content: '[+]'}
.fa-uncheck::after { content: '[-]'}
.hide { display: none }
Click on left '[-]' to mark task as done, type enter to add new, click 'x' to delete
<div class="container-fluid to-do-wrapper">
<ul class="list" id="toDo"></ul>
</div>
<template id="item">
<li class="new-list">
<i class="fas ${check}"
onclick="check(${i})"></i>
<input type="text" placeholder="Create a new list"
class="input-new-list ${done}"
value="${text}" id="inp${i}"
onchange="newItem(${i})"
oninput="change(this, ${i})"/>
<i class="fas fa-times ${hide}" onclick="del(${i})">x</i>
</li>
</template>
答案 1 :(得分:1)
我朝着不同的方向发展,将数据作为信息存储在DOM中,并提供了生成JS对象的功能,该JS对象表示按需列出待办事项列表数据。我在回答中使用了Kamil的CSS,但做了些微改动。
const list = document.querySelector('ul.list');
document.addEventListener('keypress', function(e) {
const eventTarget = e.target;
if (e.keyCode === 13 && eventTarget.parentElement && eventTarget.parentElement.classList.contains('new-item')) {
const clonedListItem = eventTarget.parentElement.cloneNode(true);
clonedListItem.classList.remove('new-item');
const icons = clonedListItem.querySelectorAll('i');
icons.forEach(el => el.classList.remove('hidden'));
const [doneIcon, deleteIcon] = icons;
doneIcon.addEventListener('click', () => toggleDone(clonedListItem));
deleteIcon.addEventListener('click', () => deleteItem(clonedListItem));
list.insertBefore(clonedListItem, eventTarget.parentElement);
eventTarget.removeAttribute('placeholder');
eventTarget.value = '';
}
});
document.getElementById('generateJSON').addEventListener('click', () => {
const data = [...document.querySelectorAll('ul.list li')]
.filter(li => !li.classList.contains('new-item'))
.map(li => ({
text: li.querySelector('input[type="text"]').value,
done: li.classList.contains('done')
}));
console.log('data', data);
});
function toggleDone(item) {
item.classList.toggle('done');
}
function deleteItem(item) {
item.remove();
}
ul {
list-style-type: none;
}
.fas {
cursor: pointer
}
li.done input[type="text"] {
background: #dfd
}
.input-new-list {
margin: 5px
}
li i.fa-check::after {
content: '[+]'
}
li.done i.fa-check::after {
content: '[-]'
}
.hidden {
display: none;
}
<ul class="list">
<li class="new-item">
<i class="fas fa-check hidden"></i>
<input type="text" placeholder="Create a new list" />
<i class="fas hidden" id="cross">x</i>
</li>
</ul>
<input type="button" id="generateJSON" value="Generate JSON" />