質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

Q&A

解決済

1回答

1031閲覧

ノート作成、削除するとき、削除ボタン+confirmメソッドの組み合わせについて教えてください。

kinsncn

総合スコア34

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

0グッド

0クリップ

投稿2021/07/31 14:05

編集2021/07/31 14:36

ノート作成アプリですが、削除ボタンで削除する前に確認にする機能を入れました。
削除ボタンをクリックしたとき、OK⇒削除実施、キャンセル⇒削除実施しないようにしたいですが、
キャンセルしてもノートが削除されるので、どこが間違っているか知りたいです。
ぜひ教えてください。

HTML

1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <link rel="shortcut icon" href="favicon.png" type="image/png"> 7 <link rel="stylesheet" href="style.css"> 8 <script defer src="note.js"></script> 9 <title>Note Taker Application</title> 10</head> 11<body> 12 <div class="modal-container"> 13 <div class="modal"> 14 <button class="modal__btn">&times;</button> 15 <h2 class="modal__title">Title here</h2> 16 <p class="modal__body">Body here</p> 17 </div> 18 </div> 19 <div class="form-container"> 20 <h1>~メモ帳~</h1> 21 <!-- <h3>Add a New Note:</h3> --> 22 <form> 23 <label for="title">Title 24 <input type="text" id="title" placeholder="Enter a note title."> 25 </label> 26 <label for="note">Note 27 <textarea type="text" id="note" cols="30" rows="25" placeholder="Enter note text."></textarea> 28 </label> 29 <input type="submit"> 30 </form> 31 </div> 32 <div class="note-container"></div> 33</body> 34</html>

Javascrip

1// Global Query Selectors 2const noteContainer = document.querySelector('.note-container'); 3const modalContainer = document.querySelector('.modal-container'); 4const form = document.querySelector('form'); 5const titleInput = document.querySelector('#title'); 6 7// Class: for creating a new note 8class Note { 9 constructor(title, body) { 10 this.title = title; 11 this.body = body; 12 this.id = Math.random(); 13 } 14} 15 16/// /LOCAL STORAGE//// 17// Function: Retreive notes from local storage 18function getNotes(){ 19 let notes; 20 if(localStorage.getItem('noteApp.notes') === null){ 21 notes = []; 22 } else { 23 notes = JSON.parse(localStorage.getItem('noteApp.notes')); 24 } 25 return notes; 26} 27 28// Function: Add a note to local storage 29function addNotesToLocalStorage(note){ 30 const notes = getNotes(); 31 notes.push(note); 32 localStorage.setItem('noteApp.notes', JSON.stringify(notes)); 33} 34 35// Function: remove a note from local storage 36function removeNote(id) { 37 if(window.confirm('削除しますか?')) { 38 const notes = getNotes(); 39 notes.forEach((note, index) => { 40 if (note.id === id){ 41 notes.splice(index, 1); 42 } 43 localStorage.setItem('noteApp.notes', JSON.stringify(notes)); 44 }) 45 } else { 46 window.alert('操作がキャンセルされました。') 47 } 48} 49 50/// /UI UPDATES//// 51// Function: Create new note in UI 52function addNoteToList(note) { 53 const newUINote = document.createElement('div'); 54 newUINote.classList.add('note'); 55 newUINote.innerHTML = ` 56 <span hidden>${note.id}</span> 57 <h2 class="note__title">${note.title}</h2> 58 <p class="note__body">${note.body}</p> 59 <div class="note__btns"> 60 <button class="note__btn note__view">View Detail</button> 61 <button class="note__btn note__delete">Delete Note</button> 62 </div> 63 `; 64 noteContainer.appendChild(newUINote); 65} 66 67// Function: Show notes in UI 68function displayNotes(){ 69 const notes = getNotes(); 70 notes.forEach(note => { 71 addNoteToList(note); 72 }) 73} 74 75// Function: Show alert message 76function showAlertMessage(message, alertClass){ 77 const alertDiv = document.createElement('div'); 78 alertDiv.className = `message ${alertClass}`; 79 alertDiv.appendChild(document.createTextNode(message)); 80 form.insertAdjacentElement('beforebegin', alertDiv); 81 titleInput.focus(); 82 setTimeout(() => alertDiv.remove(), 2000) 83} 84 85// Function: View note in modal 86function activateNoteModal(title, body){ 87 const modalTitle = document.querySelector('.modal__title'); 88 const modalBody = document.querySelector('.modal__body'); 89 modalTitle.textContent = title; 90 modalBody.textContent = body; 91 modalContainer.classList.add('active'); 92} 93 94// Event: Close Modal 95const modalBtn = document.querySelector('.modal__btn').addEventListener('click', () => { 96 modalContainer.classList.remove('active'); 97}) 98 99// Event: Note Buttons 100noteContainer.addEventListener('click', (e) => { 101 if(e.target.classList.contains('note__view')){ 102 const currentNote = e.target.closest('.note'); 103 const currentTitle = currentNote.querySelector('.note__title').textContent; 104 const currentBody = currentNote.querySelector('.note__body').textContent; 105 activateNoteModal(currentTitle, currentBody); 106 } 107 if(e.target.classList.contains('note__delete')){ 108 const currentNote = e.target.closest('.note'); 109 showAlertMessage('Your note was permanently deleted', 'remove-message'); 110 currentNote.remove(); 111 const id = currentNote.querySelector('span').textContent; 112 removeNote(Number(id)) 113 } 114}) 115 116// Event: Display Notes 117document.addEventListener('DOMContentLoaded', displayNotes) 118 119// Event: Note Form Submit 120form.addEventListener('submit', (e) => { 121 e.preventDefault(); 122 const noteInput = document.querySelector('#note'); 123 124 // validate inputs 125 if(titleInput.value.length > 0 && noteInput.value.length > 0){ 126 const newNote = new Note(titleInput.value, noteInput.value); 127 addNoteToList(newNote); 128 addNotesToLocalStorage(newNote); 129 titleInput.value = ''; 130 noteInput.value = ''; 131 showAlertMessage('Note successfully added', 'success-message'); 132 titleInput.focus(); 133 } else { 134 showAlertMessage('Please add both a title and a note', 'alert-message'); 135 } 136}); 137

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

問題は、削除ボタン を押したときのイベントにあります。

javascript

1 2// Event: Note Buttons 3noteContainer.addEventListener('click', (e) => { 4 if (e.target.classList.contains('note__view')) { 5 const currentNote = e.target.closest('.note'); 6 const currentTitle = currentNote.querySelector('.note__title').textContent; 7 const currentBody = currentNote.querySelector('.note__body').textContent; 8 activateNoteModal(currentTitle, currentBody); 9 } 10 if (e.target.classList.contains('note__delete')) { 11 const currentNote = e.target.closest('.note'); 12 showAlertMessage('Your note was permanently deleted', 'remove-message'); 13 currentNote.remove(); // ここで消えちゃう。 14 const id = currentNote.querySelector('span').textContent; 15 removeNote(Number(id)) 16 } 17})

よく見ると、削除の確認をするまえに、currentNote.remove() が実行されてしまっています。
なので、削除しない判断をした場合でも、削除ボタンをクリックした時点で当該ノードが消えてしまいます。

変更したコード

javascript

1// Event: Note Buttons 2noteContainer.addEventListener('click', (e) => { 3 if (e.target.classList.contains('note__view')) { 4 const currentNote = e.target.closest('.note'); 5 const currentTitle = currentNote.querySelector('.note__title').textContent; 6 const currentBody = currentNote.querySelector('.note__body').textContent; 7 activateNoteModal(currentTitle, currentBody); 8 } 9 if (e.target.classList.contains('note__delete')) { 10 const currentNote = e.target.closest('.note'); 11 const id = currentNote.querySelector('span').textContent; 12 removeNote(currentNote, Number(id)) 13 } 14}) 15 16// Function: remove a note from local storage 17function removeNote(currentNote, id) { 18 if (window.confirm('削除しますか?') == true) { 19 const notes = getNotes(); 20 notes.forEach((note, index) => { 21 if (note.id === id) { 22 notes.splice(index, 1); 23 } 24 localStorage.setItem('noteApp.notes', JSON.stringify(notes)); 25 }); 26 showAlertMessage('Your note was permanently deleted', 'remove-message'); 27 currentNote.remove(); 28 } else { 29 window.alert('操作がキャンセルされました。') 30 } 31}

removeNote に 新しく currentNote 引数を追加して、削除する選択の場合は、currentNote.remove() が動きます。

投稿2021/07/31 16:56

編集2021/07/31 18:02
gah2s

総合スコア9

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kinsncn

2021/08/01 00:04

ありがとうございました。 丁寧なご説明、非常に助かりました。 今後ともよろしくお願いいたします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問