Итак, я создаю веб-сайт как часть школьного проекта, который представляет собой список дел, в который вы вводите дату и время задания, и в нем появляется примечание с вашей информацией.
Я должен использовать локальное хранилище, и оно прекрасно работает для хранения заметок и их восстановления после обновления или закрытия браузера и повторного открытия.
Проблема в том, что когда я удаляю заметку с помощью «onclick = 'this.parentElement.remove ()» на значке, который появляется в заметке, я не знаю, как получить доступ к тому же месту в массиве, где хранятся все заметки.
Я добавлю свой код, и я надеюсь, что он достаточно ясно понял, о чем я спрашиваю, впервые попробовав это здесь.
var tasks = [];
// onclick='this.parentElement.remove()'
function initializenotes(){
var backup = JSON.parse(localStorage.getItem("tasks"));
if(backup.length>0){
tasks = backup;
}
console.log(backup);
console.log(tasks);
for(var i = 0; i < backup.length; i++){
var container = document.getElementById("taskcontainer");
var card = document.createElement("div");
card.className = "taskcard";
card.innerHTML = "<span class='taskstyle'>" + backup[i].task + "</span>"
+"<span class='datestyle'>" + backup[i].date + "</span>" + "<span
class='timestyle'>" + backup[i].time + "</span>" + "<i class='fas fa-
times
iconstyle' onclick='this.parentElement.remove();deletenote()'>" + "
</i>";
container.append(card);
}
}
initializenotes();
function add(){
var task = document.forms["inputform"]["task"].value;
var date = document.forms["inputform"]["date"].value;
var time = document.forms["inputform"]["time"].value;
if(validation(task, date) == true){
tasks.push(createobj(task, date, time));
localStorage.setItem("tasks", JSON.stringify(tasks));
var taskindex = tasks.length -1;
var card = document.createElement("div");
var container = document.getElementById("taskcontainer");
card.className = "taskcard";
card.innerHTML = "<span class='taskstyle'>" + tasks[taskindex].task + "
</span>" +"<span class='datestyle'>" + tasks[taskindex].date + "</span>"
+ "
<span class='timestyle'>" + tasks[taskindex].time + "</span>" + "<i
class='fas fa-times iconstyle'
onclick='this.parentElement.remove();deletenote()'>" + "</i>";
container.append(card);
document.getElementById("errormsg").innerHTML = "";
var task = document.forms["inputform"]["task"].value = "";
var date = document.forms["inputform"]["date"].value = "";
var time = document.forms["inputform"]["time"].value = "";
}
}
function deletenote(){
console.log("got into it");
}
function createobj(task, date, time){
var obj = {
task:task,
date:date,
time:time
}
return obj;
}
function validation(task,date){
if(task == ""){
document.getElementById("errormsg").innerHTML = "Task required";
return false;
}
else if(date == ""){
document.getElementById("errormsg").innerHTML = "Date required";
return false;
}
else{
return true;
}
}
А вот HTML-код (извините, что не публиковал ранее):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!--font awesome-->
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.6.1/css/all.css"
integrity="sha384-
gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP"
crossorigin="anonymous">
<!-- bootstrap -->
<link rel="stylesheet" it didnt let me add the bootstrap dir, so
its supposed to be here
<!-- my own css -->
<link rel="stylesheet" href="style.css">
<title>proj</title>
</head>
<body>
<div class="container w-50">
<div class="row mt-2">
<div class="col">
<h1 class="text-center headfont">My Task Board</h1>
</div>
</div>
<div class="row">
<div class="col">
<div class="row">
<form name="inputform">
</div>
<div class="row mt-3">
<div class="col-1 shulayim"></div>
<div class="col-11 pl-0"><input type="text"
class="form-control" disabled></div>
</div>
<div class="row">
<div class="col-1 removeTopBorder shulayim"></div>
<div class="col-11 pl-0"><input name="task"
type="text" class="form-control removeTopBorder" placeholder="Your Task">
</div>
</div>
<div class="row">
<div class="col-1 removeTopBorder shulayim"></div>
<div class="col-11 pl-0"><input name="date"
type="date" class="form-control removeTopBorder" id="dateid"></div>
</div>
<div class="row">
<div class="col-1 removeTopBorder shulayim"></div>
<div class="col-11 pl-0"><input name="time"
type="time" class="form-control removeTopBorder" id="timeid"></div>
</div>
<div class="row">
<div class="col-1 removeTopBorder shulayim"></div>
<div class="col-11 pl-0"><input type="text"
class="form-control removeTopBorder" disabled></div>
</div>
<div class="row mt-3">
<div class="col-3 offset-3"><button type="button"
onclick="add()" class="btn btn-dark btn-lg">Add task</button></div>
<div class="col-6"><button type="reset" class="btn
btn-dark btn-lg">Reset form</button></div>
</div>
<div class="row mt-3">
<div class="col-12">
<p id="errormsg" class="errmsg">Note: Task and
finish date are required</p>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row mt-3">
<div class="col-12">
<div id="taskcontainer">
</div>
</div>
</div>
</div>
<!-- bootstrap scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-
q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script
once again its not letting me add some too long stuff so its here, the
bootstrap scripts
<!-- my own script -->
<script src="scripts.js" type="text/javascript"></script>
</body>
</html>
Я действительно старался изо всех сил, чтобы сделать отступ правильно, но я либо не понимаю, как это работает, либо что-то прослушивается, потому что иногда, когда я нажимаю пробел, он просто идет вниз по строке, и я никогда не могу правильно отформатировать его как код.
надеюсь, что это читабельно
Попробуем все добавить в jfiddle
var tasks = [];
// onclick='this.parentElement.remove()'
function initializenotes() {
var backup = JSON.parse(localStorage.getItem("tasks"));
if (backup.length > 0) {
tasks = backup;
}
console.log(backup);
console.log(tasks);
for (var i = 0; i < backup.length; i++) {
var container = document.getElementById("taskcontainer");
var card = document.createElement("div");
card.className = "taskcard";
card.innerHTML = "<span class='taskstyle'>" + backup[i].task + "</span>" + "<span class='datestyle'>" + backup[i].date + "</span>" + "<span class='timestyle'>" + backup[i].time + "</span>" + "<i class='fas fa-times iconstyle' onclick='this.parentElement.remove();deletenote()'>" + "</i>";
container.append(card);
}
}
initializenotes();
function add() {
var task = document.forms["inputform"]["task"].value;
var date = document.forms["inputform"]["date"].value;
var time = document.forms["inputform"]["time"].value;
if (validation(task, date) == true) {
tasks.push(createobj(task, date, time));
localStorage.setItem("tasks", JSON.stringify(tasks));
var taskindex = tasks.length - 1;
var card = document.createElement("div");
var container = document.getElementById("taskcontainer");
card.className = "taskcard";
card.innerHTML = "<span class='taskstyle'>" + tasks[taskindex].task + "</span>" + "<span class='datestyle'>" + tasks[taskindex].date + "</span>" + "<span class='timestyle'>" + tasks[taskindex].time + "</span>" + "<i class='fas fa-times iconstyle' onclick='() => { this.parentElement.remove();deletenote(taskindex)}'>" + "</i>";
container.append(card);
document.getElementById("errormsg").innerHTML = "";
var task = document.forms["inputform"]["task"].value = "";
var date = document.forms["inputform"]["date"].value = "";
var time = document.forms["inputform"]["time"].value = "";
}
}
function deletenote() {
var taskindex = tasks.length - 1;
console.log("got into it");
tasks.splice(taskindex, 1);
localStorage.setItem("tasks", JSON.stringify(tasks));
}
function createobj(task, date, time) {
var obj = {
task: task,
date: date,
time: time
}
return obj;
}
function validation(task, date) {
if (task == "") {
document.getElementById("errormsg").innerHTML = "Task required";
return false;
} else if (date == "") {
document.getElementById("errormsg").innerHTML = "Date required";
return false;
} else {
return true;
}
}
body {
background-image: url("img/body-background.jpg");
}
.headfont {
font-family: cursive;
font-size: 4em;
}
.shulayim {
border: 1px solid #0f5aa5;
border-left: 0;
border-right: 0;
background-color: #fcfcfc;
}
.removeTopBorder {
border-top: 0 !important;
}
.form-control::-webkit-input-placeholder {
opacity: 0.7;
}
.form-control:-ms-input-placeholder {
opacity: 0.7;
}
.form-control::-ms-input-placeholder {
opacity: 0.7;
}
.form-control::placeholder {
opacity: 0.7;
}
.taskcard {
position: relative;
width: 13em;
height: 19em;
background-color: #ffff99;
border: 1px solid #532f00;
border-top: 0;
border-bottom: 0;
border-radius: 13% 32% 10% 12% / 0% 8% 0% 29%;
display: inline-block;
margin-right: 3em;
margin-left: 3em;
margin-top: 1.4em;
margin-bottom: 1.4em;
padding-left: 0.3em;
padding-top: 0.7em;
padding-bottom: 0.7em;
}
.taskcard:hover .iconstyle {
opacity: 1;
}
.taskstyle {
display: inline-block;
position: absolute;
height: 10.66em;
width: 7.61em;
top: 1.2em;
left: 0.5em;
font-size: 1.6em;
font-family: cursive;
overflow: auto;
word-wrap: break-word;
color: #323538;
}
.datestyle {
display: inline-block;
position: absolute;
top: 0.2em;
left: 0.6em;
font-size: 1.2em;
}
.timestyle {
display: inline-block;
position: absolute;
top: 0.2em;
right: 0.6em;
font-size: 1.2em;
}
.borderfix {
border-bottom: 1px solid #0f5aa5;
border-top: 1px solid #0f5aa5;
}
#dateid::before {
content: 'Finish date';
margin-right: 0.6em;
color: #6c757d;
opacity: 0.7;
}
#timeid::before {
content: 'Deadline';
margin-right: 1.5em;
color: #6c757d;
opacity: 0.7;
}
.errmsg {
font-size: 2em;
font-weight: bolder;
color: #2f64a8;
}
.iconstyle {
opacity: 0;
position: absolute;
top: 0.7em;
right: 4.4em;
}
.form-control {
border-radius: 0;
border: 1px solid #0f5aa5;
border-right: 0;
border-left-color: red !important;
}
input[type="text"],
textarea,
.form-control:focus {
outline: none;
-webkit-box-shadow: none !important;
box-shadow: none !important;
border: 1px solid #0f5aa5;
border-right: 0;
background-color: #fcfcfc;
}
.form-control:disabled,
.form-control[readonly] {
background-color: #fcfcfc;
opacity: 1;
}
.btn,
.btn:focus {
border: 1px solid #13688a;
width: 6em;
height: 2.5em;
font-size: 1.7em;
padding: 0.2em;
-webkit-box-shadow: 5px 5px 7px rgba(33, 33, 33, 0.7);
box-shadow: 5px 5px 7px rgba(33, 33, 33, 0.7);
}
/*# sourceMappingURL=style.css.map */
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!--font awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous">
<!-- bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- my own css -->
<link rel="stylesheet" href="style.css">
<title>proj</title>
</head>
<body>
<div class="container w-50">
<div class="row mt-2">
<div class="col">
<h1 class="text-center headfont">My Task Board</h1>
</div>
</div>
<div class="row">
<div class="col">
<div class="row">
<form name="inputform">
</div>
<div class="row mt-3">
<div class="col-1 shulayim"></div>
<div class="col-11 pl-0"><input type="text" class="form-control" disabled></div>
</div>
<div class="row">
<div class="col-1 removeTopBorder shulayim"></div>
<div class="col-11 pl-0"><input name="task" type="text" class="form-control removeTopBorder" placeholder="Your Task"></div>
</div>
<div class="row">
<div class="col-1 removeTopBorder shulayim"></div>
<div class="col-11 pl-0"><input name="date" type="date" class="form-control removeTopBorder" id="dateid"></div>
</div>
<div class="row">
<div class="col-1 removeTopBorder shulayim"></div>
<div class="col-11 pl-0"><input name="time" type="time" class="form-control removeTopBorder" id="timeid"></div>
</div>
<div class="row">
<div class="col-1 removeTopBorder shulayim"></div>
<div class="col-11 pl-0"><input type="text" class="form-control removeTopBorder" disabled></div>
</div>
<div class="row mt-3">
<div class="col-3 offset-3"><button type="button" onclick="add()" class="btn btn-dark btn-lg">Add task</button></div>
<div class="col-6"><button type="reset" class="btn btn-dark btn-lg">Reset form</button></div>
</div>
<div class="row mt-3">
<div class="col-12">
<p id="errormsg" class="errmsg">Note: Task and finish date are required</p>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row mt-3">
<div class="col-12">
<div id="taskcontainer">
</div>
</div>
</div>
</div>
<!-- bootstrap scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<!-- my own script -->
<script src="scripts.js" type="text/javascript"></script>
</body>
</html>