Как удалить элемент из DOM и из локального хранилища

#javascript #jquery

#javascript #jquery

Вопрос:

Я создаю своего рода «контроллер проблем» с простым JavaScript, где проблемы могут быть открыты и закрыты. Я могу добавить его в DOM и в локальное хранилище, но я не могу удалить его из DOM или из локального хранилища.

Какой самый простой способ сделать это, используя обычный JS или Jquery, без необходимости «добавлять / создавать новый идентификатор» для каждой проблемы?

Это мой код (я не тратил время на стиль и не создавал «функцию проверки»):

 <body>
  <label for="issue"></label><textarea name="issue" id="description" cols="30" rows="10"></textarea>
  <label for="severity">Choose the Severity:</label>
<select id="severity" name="severity">
  <option value="critical">Critical</option>
  <option value="important">Important</option>
  <option value="casual">Casual</option>
  <option value="minor">Minor</option>
</select>

<label for="assign"></label><input type="text" name="assign" id="assign">

<button id="createButton">Create issue</button>

<div class="box" id="box"></div>
</body>
 

Это мой JS:

 const ADD_ISSUE_TO_STORAGE = 'keyIssue'

const ELEMENTS = {
    description : document.getElementById('description'),
    severity : document.getElementById('severity'),
    assign : document.getElementById('assign'),
    createButton : document.getElementById('createButton'),
    issueToDo: document.getElementById('issueToDo'),
    severityKind: document.getElementById('severityKind'),
    assignedFor: document.getElementById('assignedFor'),
}
// ------- Event listeners -----//

ELEMENTS.createButton.addEventListener('click', function (){
       createIssue() 
})
// --------- functions ---//

function createIssue(){ 

         issue = { 
            issueDiscription: ELEMENTS.description.value,
            issueSeverity: ELEMENTS.severity.value,
            issueAssign: ELEMENTS.assign.value,
        }
            const isValid = validations(issue)
                if (isValid) {
                    addToStorage(issue);
                    showIssue(issue);
                    clearForm()
            }
}

function validations(issue){
    return true
}

function clearForm(){
    ELEMENTS.description.value = ''
    ELEMENTS.severity.value = ''
    ELEMENTS.assign.value =''
}

function addToStorage(issue){ 
    issueInStorage = JSON.parse(window.localStorage.getItem(ADD_ISSUE_TO_STORAGE)) || []
    issueInStorage.push(issue)
    window.localStorage.setItem(ADD_ISSUE_TO_STORAGE, JSON.stringify(issueInStorage))
}


function deleteIssue(e){
document.getElementById.getElementById('delete').addEventListener('click', localStorage.removeItem(e))
     $(document).ready(function(){
        $("#issue").css("display", "none");
       });
    }

 function showIssue(issue){
   const str =  `<div id='issue'>
                    <h1 id="issueToDo">${description.value}</h1>
                    <h3 id="severityKind">${severity.value}</h3>
                    <h4 id="assignedFor">${assign.value}</h4>
                    <button  id ='delete' onclick='deleteIssue(e)'> Delete Issue </button>
                </div>`
    document.getElementById('box').innerHTML  = str 
 }

Thanks
 

Ответ №1:

Попробуйте следующее (я добавил каждую проблему со своим собственным ключом в локальное хранилище и передаю ключ removeItem — ключом будет keyissue уникальный номер проблемы)

Уникальный номер проблемы — это идентификатор описания проблемы (который я передаю обработчику событий при нажатии кнопки и deleteIssue())

     <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
</head>

    
    
        <body>
            <label for="issue"></label><textarea name="issue" id="description" cols="30" rows="10"></textarea>
            <label for="severity">Choose the Severity:</label>
          <select id="severity" name="severity">
            <option value="critical">Critical</option>
            <option value="important">Important</option>
            <option value="casual">Casual</option>
            <option value="minor">Minor</option>
          </select>
          <label for="assign"></label><input type="text" name="assign" id="assign">

    <button id="createButton">Create issue</button>

    <div class="box" id="box"></div>
</body>

    <script>
        const ADD_ISSUE_TO_STORAGE = 'keyIssue'
        let issueNum = 0;
const ELEMENTS = {
    description : document.getElementById('description'),
    severity : document.getElementById('severity'),
    assign : document.getElementById('assign'),
    createButton : document.getElementById('createButton'),
    issueToDo: document.getElementById('issueToDo'),
    severityKind: document.getElementById('severityKind'),
    assignedFor: document.getElementById('assignedFor'),
}
// ------- Event listeners -----//

ELEMENTS['createButton'].addEventListener('click', function (){
       createIssue(); 
})
// --------- functions ---//

function createIssue(){ 

         issue = { 
            issueDiscription: ELEMENTS.description.value,
            issueSeverity: ELEMENTS.severity.value,
            issueAssign: ELEMENTS.assign.value,
        }
            const isValid = validations(issue)
                if (isValid) {
                    addToStorage(issue);
                    showIssue(issue);
                    clearForm()
            }
}

function validations(issue){
    return true
}

function clearForm(){
    ELEMENTS.description.value = ''
    ELEMENTS.severity.value = ''
    ELEMENTS.assign.value =''
}

function addToStorage(issue){ 

    window.localStorage.setItem(ADD_ISSUE_TO_STORAGE   (  issueNum),issue)
    console.log(localStorage);
}

function deleteIssueElements (obj)
{
    console.log("in delete");
    localStorage.removeItem(ADD_ISSUE_TO_STORAGE obj);
   document.getElementById('box').removeChild(document.getElementById('issue'));
}
function deleteIssue(obj){
document.getElementById('delete').addEventListener('click', deleteIssueElements(obj))
    }

 function showIssue(issue){
   const str =  `<div id='issue'>
                    <h1 id="${issueNum}">${description.value}</h1>
                    <h3 id="severityKind">${severity.value}</h3>
                    <h4 id="assignedFor">${assign.value}</h4>
                    <button  id ='delete' onclick='deleteIssue("${issueNum}")'> Delete Issue </button>
                </div>`
    document.getElementById('box').innerHTML  = str 
 }

    </script>
</html>
 

Отредактировано
Описание проблемы должно быть уникальным, иначе нет смысла иметь две проблемы с одинаковым описанием. Итак, я использую описание проблемы в качестве ключа для связанного ключа div и localStorage в моей логике

JavaScript

     const ELEMENTS = {

    description : document.getElementById('description'),
    severity : document.getElementById('severity'),
    assign : document.getElementById('assign'),
    createButton : document.getElementById('createButton'),
    issueToDo: document.getElementById('issueToDo'),
    severityKind: document.getElementById('severityKind'),
    assignedFor: document.getElementById('assignedFor'),
}
// ------- Event listeners -----//

ELEMENTS['createButton'].addEventListener('click', function (){
       createIssue(); 
})
// --------- functions ---//

function createIssue(){ 

         issue = { 
            issueDiscription: ELEMENTS.description.value,
            issueSeverity: ELEMENTS.severity.value,
            issueAssign: ELEMENTS.assign.value,
        }
            const isValid = validations(issue)
                if (isValid) {
                    addToStorage(issue);
                    showIssue(issue);
                    clearForm()
            }
}

function validations(issue){
    // case the user did not enter any description or spaces
    if ( issue.issueDiscription.trim() === '')
     {
         alert ("Issue description is required");
        return false;
     }
     for (let i in localStorage) {
         if (i == issue.issueDiscription) {
             window.alert("This entry already exists (duplicate issue description)");
             return false;
         } 
     }
    return true;
}

function clearForm(){
    ELEMENTS.description.value = ''
    ELEMENTS.severity.value = ''
    ELEMENTS.assign.value =''
}
// Issue description will be the key for each issue (Because the issue description has to be unique)
function addToStorage(issue){ 
    window.localStorage.setItem(issue.issueDiscription,issue)
}

function deleteIssueElements (issueDescription)
{
    localStorage.removeItem(issueDescription);
   document.getElementById('box').removeChild(document.getElementById(issueDescription));
}
function deleteIssue(issueDescription){
    document.getElementById('delete').addEventListener('click', deleteIssueElements(issueDescription))
}

 function showIssue(issue){
     // The id of the div will be the issue description as this always has to be unique
   const str =  `<div id='${description.value}'>
                    <h1 id="issueToDo">${description.value}</h1>
                    <h3 id="severityKind">${severity.value}</h3>
                    <h4 id="assignedFor">${assign.value}</h4>
                    <button  id ='delete' onclick='deleteIssue("${description.value}")'> Delete Issue </button>
                </div>`
    document.getElementById('box').innerHTML  = str 
 }