我在javascript中有一个待办事项列表,并决定使用localstorage来保存列表。事情是列表的个别删除项目按钮现在不工作,没有单击按钮,然后按Enter键。这只发生在chrome和safari上。在firefox中一切正常,所以我不确定问题究竟是什么,这是我第一次尝试使用localstorage。
这是整个代码库,因为我不确定哪个部分可能导致问题。
var input = document.querySelector('input[name=todoItem]'),
btnAdd = document.querySelector('button[name=add]'),
btnClear = document.querySelector('button[name=clear]'),
btnSave = document.querySelector('button[name=save]'),
list = document.querySelector('.todo'),
storeList = [];
list.innerHTML = window.localStorage.getItem('list');
function renderTodos(){
//Cached array length for use in for loop
var listLength = storeList.length,
//Created list item and button
el = document.createElement('li'),
x = document.createElement('button');
//Set text for remove button
x.setAttribute('class', 'remove');
x.innerHTML = '<i class="fa fa-trash-o fa-2x"></i>';
//Loop for adding items to array and appending items to list
for(var i = 0; i < listLength; i++){
el.innerHTML = storeList[i];
list.appendChild(el);
el.appendChild(x);
}
//Clear out and put focus back in input box
input.value = '';
input.focus();
}
//Add todo item to list
function addTodos(e){
//Check to see that input isn't empty or only spaces with no characters
// and add todo item if add button is clicked or enter key is pushed
if(input.value.trim() !== '' && (e.which ===13 || e.which ===1)){
storeList.push(input.value);
renderTodos();
}
else if(input.value.trim() === '' && (e.which ===1 || e.which === 13)){
alert('Please Enter A Valid Item!');
input.focus();
}
}
function removeItem(e){
var node = e.target;
var attr = node.getAttribute('class');
if(attr === 'remove'){
node = node.parentNode;
node.parentNode.removeChild(node);
}
}
//Clear the whole list
function clearList(){
// make list empty
list.innerHTML = '';
storeList.splice(0, storeList.length);
renderTodos();
}
//Initialize listeners and show saved list from local storage on page load
function init(){
btnSave.addEventListener('click', function(){
window.localStorage.setItem('list', list.innerHTML);
});
list.addEventListener('click', removeItem);
btnAdd.addEventListener('click', addTodos);
btnClear.addEventListener('click', clearList);
input.addEventListener('keydown', addTodos);
}
window.onload = init;
一切正常,但带有垃圾桶图标的按钮只有在点击后才会生效,然后按下回车键。
答案 0 :(得分:0)
由于某些原因,firefox正在制作点击<i>
标记的目标,而Chrome和safari的点击目标是<button>
标记。我根据浏览器的不一致性为每个目标做了一个条件修复。
<button><i></i></button>