2016-09-24 146 views
1

如何正確刪除列表項目?Javascript - 刪除列表項目

我一直使用下面這行代碼來刪除一個項目,而是這個刪除整個列表本身:

var list = document.getElementById("shoppinglist"); 

list.onclick = function() { list.parentNode.removeChild(list);} 

我一直對如何做到這一點的在線搜索和同類代碼保持出現,我不知道如何解決這個問題。我認爲生成的列表項是「購物清單」的子項。

我對Javascript很新,我知道這是一個新手的錯誤,但我會非常感謝任何幫助。謝謝。

<!doctype html> 
 
<html dir="ltr" lang="en-gb"> 
 
<head> 
 
<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
 
<style> 
 
body { 
 
\t /* Sets the width then uses the margin auto feature to centre the page in the browser */ 
 
\t width:800px; 
 
\t margin: 0px auto; /*0px top/bottom auto left/right */ 
 
\t font-size:10px; /* By default fonts are usually 16px but may not be in some browsers */ 
 
} 
 
p, li { 
 
\t font-size:1.5em; /* Set all text to be 1.5 * overall font size = 15 pixels */ 
 
} 
 
section { 
 
\t /* each of the two sections will use just under half the width of the width of the body */ 
 
\t width:395px; 
 
\t display:block; 
 
} 
 
#choices { 
 
\t /* float the choices list to the left of the page */ 
 
\t float:left; 
 
\t background-color: #FFFF99; 
 
} 
 
#cart { 
 
\t /* float the shopping cart to the right of the page */ 
 
\t float:right; 
 
\t background-color: #7FFF00; 
 
} 
 
.cartlist { 
 
\t /* Simplify the display of the lists, removing default bullet points and indentation */ 
 
\t list-style-type:none; 
 
\t margin:0px; 
 
\t padding:0px; 
 
\t width:inherit; 
 
} 
 
.cartlist li { 
 
\t /* Set each list item to be 2* the height of the text */ 
 
\t height:2em; 
 
} 
 
.cartlist li:nth-child(odd) { 
 
\t /* Colour odd list items ie first, third, fifth etc, a different colour */ 
 
\t background-color:#eee; 
 
} 
 
#outputinfo { 
 
\t /* prevents the DIV from joining the floating behaviour so it displays below the lists */ 
 
\t clear:both; 
 
} 
 
</style> 
 
</head> 
 
<body> 
 
<section id="choices"> 
 
\t <p>Available Choices</p> 
 
\t <ul id="sourcelist" class="cartlist"> 
 
\t \t <li data-value="2.99">&pound;2.99 : Chocolate</li> 
 
\t \t <li data-value="3.49">&pound;3.49 : Cereal</li> 
 
\t \t <li data-value="0.98">&pound;0.98 : Milk</li> 
 
\t \t <li data-value="0.89">&pound;0.89 : Bread</li> 
 
\t \t <li data-value="3.79">&pound;3.79 : Coffee</li> 
 
\t \t <li data-value="2.53">&pound;2.53 : Strawberries</li> 
 
\t \t <li data-value="3.89">&pound;3.89 : Cheesecake</li> 
 
\t </ul> 
 
</section> 
 
<section id="cart"> 
 
\t <p>Shopping Cart</p> 
 
\t <ul id="shoppinglist" class="cartlist"></ul> 
 
</section> 
 
<div id="outputinfo"> 
 
\t <p><button id="calctotal">Calculate Total</button> : <span id="totalresult"></span></p> 
 
</div> 
 
</body> 
 

 
<script> 
 

 
function getTargetElement(e) { 
 
\t var targetelement=null; 
 
\t targetelement=(e.srcElement || e.target || e.toElement) 
 
\t return targetelement; 
 
} 
 

 
function calcTotal() { 
 
\t var shoppinglist=document.getElementById("shoppinglist"); 
 
\t var total=0; 
 
\t for(i=0;i<shoppinglist.children.length;i++) { 
 
\t \t total+=parseFloat(shoppinglist.children[i].getAttribute("data-value")); 
 
\t } 
 
\t var totalresult=document.getElementById("totalresult"); 
 
\t totalresult.innerHTML="&pound;"+total.toFixed(2); 
 
} 
 

 
function handleEvent(e) { 
 
\t var listclicked=getTargetElement(e); 
 
\t var newlistitem=document.createElement("li"); 
 
\t var datavalue=listclicked.getAttribute("data-value"); 
 
\t newlistitem.setAttribute("data-value",datavalue); 
 
\t newlisttext=document.createTextNode(listclicked.innerHTML) 
 
\t newlistitem.appendChild(newlisttext); 
 
\t var shoppinglist = document.getElementById("shoppinglist"); 
 
\t shoppinglist.appendChild(newlistitem); 
 
\t 
 
\t var list = document.getElementById("shoppinglist"); 
 
\t 
 
\t list.onclick = function() { list.parentNode.removeChild(list);} 
 

 

 
\t console.log(listclicked); 
 
} 
 

 
function removeItem(e){ 
 

 
\t var listclicked=getTargetElement(e); 
 
\t var node = document.getElementById('shoppinglist'); 
 
\t listclicked.parentNode.removeChild(listclicked); 
 
} 
 

 
document.onreadystatechange = function(){ 
 
\t if(document.readyState=="complete") { 
 
\t var sourcelist=document.getElementById("sourcelist"); 
 
\t 
 
\t for(i=0;i<sourcelist.children.length;i++) { 
 
\t \t \t if(document.addEventListener) { 
 
\t \t \t \t sourcelist.children[i].addEventListener("click", handleEvent, false); 
 

 
\t \t \t } else { 
 
\t \t \t \t sourcelist.children[i].attachEvent("onclick", handleEvent); 
 
\t \t \t } 
 
\t \t 
 
\t \t var totalbutton=document.getElementById("calctotal"); 
 
\t \t if(document.addEventListener) { 
 
\t \t \t totalbutton.addEventListener("click",calcTotal,false); 
 
\t \t } else { 
 
\t \t \t totalbutton.attachEvent("onclick",calcTotal); 
 
\t \t } 
 

 
\t \t } 
 

 
\t } 
 
} 
 
</script> 
 
    
 
</html>

回答

3

你不想刪除整個列表,只需點擊LI元素。

正如你似乎並不具備嵌套元素,事件委派變得更容易一些

var list = document.getElementById("shoppinglist"); 

list.addEventListener('click', function(evt) { 
    list.removeChild(evt.target); 
},false); 

FIDDLE

對於未來,如果你想nesten元素,你可以使用element.closest()

var list = document.getElementById("shoppinglist"); 

list.addEventListener('click', function(evt) { 
    var p = evt.target.closest('li'); 
    list.removeChild(p); 
}, false); 

請注意,舊版瀏覽器對closest()的支持有所欠缺,但有幾個polyfills可用如果需要的話可以

還要注意,要綁定的事件處理程序事件處理程序裏面,這是一個很大的禁忌,你的代碼做的

var sourcelist = document.getElementById("sourcelist"); 

for(i = 0; i < sourcelist.children.length; i++) { 
    sourcelist.children[i].addEventListener("click", handleEvent, false); 
    ... 

// and then 

function handleEvent(e) { 

    var list = document.getElementById("shoppinglist"); 

    list.addEventListener('click', function(evt) { 
     list.removeChild(evt.target); 
    },false); 
    .... 

相當於所以每次添加另一個列表項的列表,你綁定一個新的事件處理程序,並且它會相加,但是你只需要一個事件處理程序,讓多個事件處理程序試圖一遍又一遍地刪除同一個元素,但是它第一次被刪除。

+0

這非常有用。我非常感謝你,它給了我很多的關注和理解。我還想讚揚其他評論以及其他任何希望看到它們的人,因爲他們很有用。謝謝。 – user3361789

0
list.onclick = function() { list.parentNode.removeChild(list);} 

list是整個列表(<ul id='list'>)。您正在傾聽整個列表中的點擊。然後用list.parentNode(它給你<section id="cart">)抓取整個列表的父節點並從中刪除列表。

你的代碼正在做你剛纔告訴它做的事情。

0

像這樣:

list.removeChild(list.childNodes[indexToRemove]) 

您需要指定要刪除哪個節點。您可以通過打開控制檯中鉻試驗這一點,並粘貼如下:

var list = document.getElementById("shoppinglist"); 

console.log('List:', list) 
console.log('List children:', list.childNodes) 

var indexToRemove = 0; 

list.removeChild(list.childNodes[indexToRemove]); 

console.log('List:', list) 
console.log('List children:', list.childNodes) 
0

您可以使用此:

var list = document.getElementById("shoppinglist"); 
list.onclick = function(e) { e.target.parentNode.removeChild(e.target);} 

你可以閱讀更多關於targetcurrentTarget和結帳這個例子http://fiddle.jshell.net/hidoos/Lpz917vo/