削除ボタンがクリックされたときに、クリックしたbuttonの親要素が、liの中で何番目にあるかを取得するプログラムを書いたのですが、console.logでみたところ常に-1となってしまいうまく取得できませんでした。なにがいけないのでしょうか?
サーバーに後悔してみました→https://todo.aoicoder.com
html
1<!DOCTYPE html> 2<html lang="en"> 3 4<head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>todo</title> 8 <link rel="stylesheet" href="css/reset.css"> 9 <link rel="stylesheet" href="css/style.css"> 10</head> 11 12<body> 13 <div class="container"> 14 <h1>TODO</h1> 15 <ul id="ul"></ul> 16 <div class="add_task"> 17 <input id="write" type="text"> 18 <button id="add_btn">追加</button> 19 </div> 20 </div> 21 22 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 23 <script src="js/script.js"></script> 24</body> 25 26</html>
sass
1.container { 2 max-width: 1200px; 3 margin: 0 auto; 4 padding-left: 20px; 5 padding-bottom: 100px; 6} 7 8h1 { 9 padding-top: 100px; 10 margin-bottom: 100px; 11 position: relative; 12 font-weight: bold; 13 font-size: 60px; 14 text-align: center; 15 16 &::after { 17 content: ""; 18 position: absolute; 19 bottom: -15px; 20 display: inline-block; 21 width: 60px; 22 height: 4px; 23 left: 50%; 24 transform: translateX(-50%); 25 background-color: pink; 26 } 27} 28 29ul { 30 li { 31 padding: 50px 0; 32 text-align: center; 33 font-size: 30px; 34 border-bottom: 2px pink solid; 35 width: 80%; 36 margin: 0 auto; 37 display: flex; 38 justify-content: space-between; 39 align-items: center; 40 41 p { 42 text-align: left; 43 } 44 45 button { 46 padding: 16px 54px; 47 font-size: 24px; 48 color: blue; 49 border: 3px solid blue; 50 background: white; 51 transition: all .5s; 52 white-space: nowrap; 53 54 &:hover { 55 color: white; 56 background: blue; 57 } 58 } 59 } 60} 61 62.add_task { 63 text-align: center; 64 padding-top: 100px; 65 input { 66 border: 1px solid; 67 text-align: left; 68 padding: 20px; 69 font-size: 24px; 70 margin-right: 30px; 71 width: 800px; 72 } 73 74 button { 75 padding: 16px 54px; 76 font-size: 24px; 77 color: pink; 78 border: 3px solid pink; 79 background: white; 80 transition: all .5s; 81 82 &:hover { 83 color: white; 84 background: pink; 85 } 86 } 87}
javascript
1script.js 2 3et count = 0 + localStorage.getItem('count'); 4 5$('#add_btn').click(function() { 6 let write = $('#write').val(); 7 let new_task = `<li class="count_li"><p>${write}</p><button>削除</button></li>`; 8 localStorage.setItem(`save_task${count}`, new_task); 9 if(write != "") { 10 $('#ul').append(localStorage.getItem(`save_task${count}`)); 11 }; 12 $('#write').val(""); 13 count += 1; 14 localStorage.setItem('count', count); 15}); 16 17$(document).on("click", "li button", function (){ 18 $(this).parent().remove(); 19 let remove_index = $('li.count_li').index($(this).parent()); 20 console.log(remove_index); 21 localStorage.removeItem(`save_task${remove_index}`); 22}); 23 24for(let i = 0; i < count; i++) { 25 $('#ul').append(localStorage.getItem(`save_task${i}`)); 26};