estou criando um armazenamento de favoritos em localStorage com JS, porém quando clico em "deletar" na maioria das vezes ele não remove o item correto, as vezes até remove porém deleta outros itens também, segue o HTML e o JS:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Site Bookmarker</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body onload="fetchBookmarks()">
<div class="container">
<div class="header clearfix">
<nav>
</nav>
<h3 class="text-muted">Bookmarker</h3>
</div>
<div class="jumbotron">
<h2>Bookmark Your Favorite Sites</h2>
<form id="myForm">
<div class="form-group">
<label>Site Name</label>
<input type="text" class="form-control" id="siteName" placeholder="Website Name">
</div>
<div class="form-group">
<label>Site URL</label>
<input type="text" class="form-control" id="siteUrl" placeholder="Website URL">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="row marketing">
<div class="col-lg-12">
<div id="bookmarksResults"></div>
</div>
</div>
<footer class="footer">
<p>© 2016 Bookmarker, Inc.</p>
</footer>
</div> <!-- /container -->
<script
src="https://code.jquery.com/jquery-3.1.1.js"
integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
crossorigin="anonymous"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Javascript:
// Listen for form submit
document.getElementById('myForm').addEventListener('submit', saveBookmark);
// Save Bookmark
function saveBookmark(e){
// Get form values
var siteName =document.getElementById('siteName').value;
var siteUrl =document.getElementById('siteUrl').value;
if(!validateForm(siteName, siteUrl)){
return false;
}
var bookmark = {
name: siteName,
url: siteUrl
}
/*
// Local Storage Test
localStorage.setItem('test', 'Hello World');
console.log(localStorage.getItem('test'));
localStorage.removeItem('test');
console.log(localStorage.getItem('test'));
*/
// Test if bookmarks is null
if(localStorage.getItem('bookmarks') === null){
// Init array
var bookmarks = [];
// Add to array
bookmarks.push(bookmark);
// Set to localStorage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
} else {
// Get bookmarks from localStorage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
// Add bookmark to array
bookmarks.push(bookmark);
// Re-set back to localStorage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
}
// Clear form
document.getElementById('myForm').reset();
// Re-fetch bookmarks
fetchBookmarks();
// Prevent form from submitting
e.preventDefault();
}
// Delete bookmark
function deleteBookmark(url){
// Get bookmarks from localStorage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
// Loop through the bookmarks
for(var i =0;i < bookmarks.length;i++){
if(bookmarks[i].url == url){
// Remove from array
bookmarks.splice(i, 1);
}
}
// Re-set back to localStorage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
// Re-fetch bookmarks
fetchBookmarks();
}
// Fetch bookmarks
function fetchBookmarks(){
// Get bookmarks from localStorage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
// Get output id
var bookmarksResults = document.getElementById('bookmarksResults');
// Build output
bookmarksResults.innerHTML = '';
for(var i = 0; i < bookmarks.length; i++){
var name = bookmarks[i].name;
var url = bookmarks[i].url;
bookmarksResults.innerHTML += '<div class="well">'+
'<h3>'+name+
' <a class="btn btn-default" target="_blank" href="'+addhttp(url)+'">Visit</a> ' +
' <a onclick="deleteBookmark(\''+url+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</h3>'+
'</div>';
}
}
// Validate Form
function validateForm(siteName, siteUrl){
if(!siteName || !siteUrl){
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if(!siteUrl.match(regex)){
alert('Please use a valid URL');
return false;
}
return true;
}
function addhttp(url) {
if (!/^(?:f|ht)tps?\:\/\//.test(url)) {
url = "http://" + url;
}
return url;
}
break
no final desseif(bookmarks[i].url == url){
que está dentro do laçofor
? É porque se ele achou o índice, não faz mais sentido continuar o laço, porque irá alterar o.length
dobookmarks
com o.splice
. Não testei, mas pode ser isso o problema.