我已经尝试了几个小时,才能通过localStorage API从列表中成功删除项目。我将项目插入列表并在将它们推入视图时查看它们没有问题。如何使用localStorage从阵列中删除项目?我写的代码如下。另一个小问题是,表单验证尚未启动,我似乎无法发现允许空输入的错误。
index.html
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="shoutout-box-pos">
<div class="shoutout-box">
<div class="shoutout-box-header">
<div class="text-center">
<div class="shoutout-header-text">
<h4>Post a shoutout</h4>
</div>
<div class="shoutout-form-container">
<form id='shoutout-form'>
<div class="form-group">
<label>Name</label>
<input class="form-control" type="text" placeholder="Customer Name" id="name" />
</div>
<div class="form-group">
<label>Tell us about your stay!</label>
<input class="form-control" type="text" placeholder="What would you like to say?" id="message" />
</div>
<div class="form-group">
<label>Which session did you take part in?</label>
<input class="form-control" type="text" id="tour_session" placeholder="Give us the date or session title" />
</div>
<div class="form-group">
<button class="bttn-bordered bttn-md bttn-primary" type="submit" value="Submit">Post Message</button>
</div>
</form>
</div>
<div class="shoutout-messages">
<ul class="messageListContainer" id="messageList">
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
app.js
// ES6 Shoutout Messages
class Shoutout {
constructor(name, message, tour_session) {
this.name = name;
this.message = message;
this.tour_session = tour_session;
}
}
class UI {
addMessageToList(Shoutmessage) {
const list = document.getElementById('messageList');
// create li element
const li = document.createElement('li');
//Insert li into ul
li.innerHTML = `
<li><strong>Customer Name: </strong> <p class='lead'>${Shoutmessage.name}</p></li>
<li><strong>Message: </strong> <p class='lead'> ${Shoutmessage.message}</p></li>
<li><strong>Tour Session: </strong> <p class='lead'> ${Shoutmessage.tour_session} </p></li>
<li><a href="#" class="delete bttn-minimal bttn-sm">Remove Shoutout<a></li>
`;
list.appendChild(li);
}
showAlert(message, className) {
// create div
const div = document.createElement('div');
// Add classes
div.className = `alert ${className}`;
// Add text
div.appendChild(document.createTextNode(message));
// Get Parent Class
const container = document.querySelector('.shoutout-form-container');
// Get form Id
const form = document.querySelector('#shoutout-form');
// Insert alert
container.insertBefore(div, form);
// Timeout after 3 seconds
setTimeout(function () {
document.querySelector('.alert').remove();
}, 3000);
}
deleteShout(target) {
if (target.className === 'delete') {
target.parentElement.parentElement.remove();
}
}
clearFields() {
document.getElementById('name').value = '';
document.getElementById('message').value = '';
document.getElementById('tour_session').value = '';
}
}
// Local Storage Class Object
class Store {
static getShoutouts() {
let messages;
if (localStorage.getItem('messages') === null) {
messages = [];
} else {
messages = JSON.parse(localStorage.getItem('messages'));
}
return messages;
}
static displayShoutouts() {
const messages = Store.getShoutouts();
messages.reverse().forEach(function (message) {
const ui = new UI;
ui.addMessageToList(message);
});
}
static addMessage(message) {
const messages = Store.getShoutouts();
messages.push(message);
localStorage.setItem('messages', JSON.stringify(messages));
}
static removeMessage(tour_session) {
const messages = Store.getShoutouts();
messages.forEach(function (message, index) {
if (message.tour_session === tour_session) {
messages.splice(index, 1);
}
});
localStorage.setItem('messages', JSON.stringify(messages));
}
}
// DOM Load Event
document.addEventListener('DOMContentLoaded', Store.displayShoutouts);
// Event Listener for add message
document.getElementById('shoutout-form').addEventListener('submit', function (e) {
//Grab form values
const name = document.getElementById('name').value,
message = document.getElementById('message').value,
tour_session = document.getElementById('tour_session').value
// Instantiate message
const msg = new Shoutout(name, message, tour_session);
// Instantiate UI
const ui = new UI();
console.log(ui);
// Validate
if (name === '' || message === '' || tour_session === '') {
//Error alert
ui.showAlert('Please fil in all fields', 'error');
} else {
// Add message to list
ui.addMessageToList(msg);
// Add to Local Storage
Store.addMessage(msg);
// Show success
ui.showAlert('Shoutout Message Added!', 'success');
// Clear fields
ui.clearFields();
}
e.preventDefault();
});
// Event Listener for delete
document.getElementById('messageList').addEventListener('click', function (e) {
// Instantiate UI
const ui = new UI();
// Delete message
ui.deleteShout(e.target);
// Remove from Local Storage
Store.removeMessage(e.target.parentElement.previousElementSibling.textContent);
// Show message
ui.showAlert('Message Removed!', 'success');
e.preventDefault();
});
答案 0 :(得分:0)
您的代码中的问题是
e.target.parentElement.previousElementSibling.textContent
可能会返回类似
“游览:$ {tour_session}”
您需要的精确tour session
位于p.lead
中的元素内
因此请尝试将tour_session选择器更改为
...
// Remove from Local Storage
Store.removeMessage(e.target.parentElement.previousElementSibling.querySelector(".lead").textContent);
...
UPD
看看这个CodePen。
答案 1 :(得分:0)
演示:https://codepen.io/anon/pen/ajpwYR?editors=0011
在您的addMessageToList()方法中,我向“删除喊叫”链接添加了一个属性tour_session
。
addMessageToList(Shoutmessage) {
const list = document.getElementById('messageList');
// create li element
const li = document.createElement('li');
//Insert li into ul
li.innerHTML = `
<li><strong>Customer Name: </strong> <p class='lead'>${Shoutmessage.name}</p></li>
<li><strong>Message: </strong> <p class='lead'> ${Shoutmessage.message}</p></li>
<li><strong>Tour Session: </strong> <p class='lead'> ${Shoutmessage.tour_session} </p></li>
<li><a href="#" class="delete bttn-minimal bttn-sm" tour_session=${Shoutmessage.tour_session}>Remove Shoutout<a></li>
`;
list.appendChild(li);
}
在事件侦听器中,将tour_session属性的值传递给removeMessage方法。
document.getElementById('messageList').addEventListener('click', function(e) {
// Instantiate UI
const ui = new UI();
// Delete message
ui.deleteShout(e.target);
// Remove from Local Storage
// console.log(e.target.getAttribute('tour_session'));
Store.removeMessage(e.target.getAttribute('tour_session'));
// Show message
ui.showAlert('Message Removed!', 'success');
e.preventDefault();
});
在deleteShout方法中,className将返回您指定的所有类的名称。因此,每次检查都会失败,并且不会从DOM中删除该节点。
deleteShout(target) {
if (target.className.split(' ').indexOf('delete') > -1) {
target.parentElement.parentElement.remove();
}
}