2017-12-03 2 views
1

アイコンをクリックすると、リスト項目を削除しようとしているテーブルがあります。クラスからliアイテムを削除します

enter image description here

私は、ゴミ箱のアイコンをクリックして、ごみ箱アイコンのみときだから、私は「アップ」そのリスト項目を削除し、他の人を移動したいです。

<div class="container"> 
    <div class="list">TO-DO LIST<div class="glyphicon glyphicon-plus"></div></div> 
    <ul class="toDoList" style="list-style: none;"> 
     <li id="addToDo"><input type='text' id="addToDoText" placeholder="Add New ToDo"></input></li> 
     <li><span><i class="fa fa-trash"></i></span>Buy Robes</li> 
     <li><span><i class="fa fa-trash"></i></span>Fight Malfoy</li> 
     <li><span><i class="fa fa-trash"></i></span>Buy New Wand</li> 
     <li><span><i class="fa fa-trash"></i></span>Kill Voldemort</li> 
     <li><span><i class="fa fa-trash"></i></span>Feed Hedwig</li> 
     <li><span><i class="fa fa-trash"></i></span>Send Owl to Sirius</li> 
     <li><span><i class="fa fa-trash"></i></span>Do Dishes</li> 
     <li><span><i class="fa fa-trash"></i></span>Wash Robes</li> 
     <li><span><i class="fa fa-trash"></i></span>Buy Hagrid's Birthday Gift</li> 
    </ul> 
</div> 

と私はアイテムを削除すると維持したいテーブルの代替色を、着色するためのコードが含まれて私のjQuery、

$(document).ready(function(){ 
    color_table(); 
}); 

function color_table(){ 
    $('.toDoList li:nth-child(odd)').addClass('alternate'); 
}; 

$('li .fa-trash').on("click", function(){ 
    var index = $(this).index(); // ...doesn't do anything. b/c no index of the class? 
    var text = $('li').text(); // gets LI text correctly of current item 
    console.log(index+" // "+text); 
    $(this).remove(); // This should remove the LI entry, not just the icon class .fa-trash. If I use $('li').remove(), it removes the entire li list! Not just the current one. 
    color_table(); 
}) 

答えて

2

あなたは先祖liを取得するためにclosest()メソッドを使用する必要があります。

$(this).closest('li').remove(); 
+0

ありがとうございます!それによってアイテムが正常に削除されます。テーブルの色が交互に変わるので、編集しました。どのように私はその色づけを保つことができますか?アイテムを削除すると、灰白白色または白灰色灰色になります。 – BruceWayne

+0

あなたは 'JS'の代わりにCSSを使うことができます。 https://jsfiddle.net/10omLxdo/ @ BruceWayne – Azim

1

あなたが代わりに親liをターゲットとすべき、あなたが使用できます。

$(this).parents('li').remove(); 

は、この情報がお役に立てば幸いです。

+0

ありがとうございます。これはちょうど@ Azimの答えへの別の方法ですか、それとも私が気づくべきであるかに大きな違いや落とし穴がありますか? – BruceWayne

+0

あなたは大歓迎です、どちらも同じトリックをしていません。 –

関連する問題