宿題として Javascript で簡単なショッピング カートの Web ページを作成しています。ショッピングカートに入っている本ごとに「アイテムを削除」ボタンを作成していますが、実装方法がわかりません。DOM ツリーを使用する必要があることはわかっていますが、その方法がわかりません。関連するコードは次のとおりです。
<script>
function addToCart(bookToAdd, priceToAdd)
{
//Create the node
var bookInfo = document.createElement();
bookInfoString = "Book: " + document.getElementById(bookToAdd).innerHTML +
" <br />Price: $" + document.getElementById(priceToAdd).innerHTML +
'<br /> <button type="button" onclick="removeFromCart(' + bookToAdd + ', ' + priceToAdd + ')">Remove from cart!</button> <br /> <br />';
bookInfo.innerHTML = bookInfoString;
//Append the node
document.getElementById('cartItems').appendChild(bookInfo);
//Update the cart total
document.getElementById('totalPrice').firstChild.nodeValue = (parseFloat(document.getElementById('totalPrice').innerHTML) + parseFloat(document.getElementById(priceToAdd).innerHTML)).toFixed(2);
}
function removeFromCart(bookToRemove, priceToRemove)
{
//Remove the node
getElementById('cartItems').removeChild(bookToRemove);
//Update the cart total
document.getElementById('totalPrice').firstChild.nodeValue = (parseFloat(document.getElementById('totalPrice').innerHTML) - parseFloat(document.getElementById(priceToRemove).innerHTML)).toFixed(2);
}
</script>
... html コードの関連部分:
<tr>
<!--Fill in the first book information-->
<td> <span class="bookName" id="book1"><b>Artificial Intelligence: A Modern Approach</b></span><br>
<img src="AI.jpeg" alt="AI Book Cover" width="100"> <br>
<b>ISBN:</b> 978-0-13-604259-4 <br>
<b>Description:</b> Artificial Intelligence: A Modern Approach, 3e offers the most comprehensive,
up-to-date introduction to the theory and practice of artificial intelligence. Number one in
its field, this textbook is ideal for one or two-semester, undergraduate or graduate-level
courses in Artificial Intelligence. <br>
<b>PRICE: $</b> <span id="price1"> 158.55 </span>
<button type="button" onclick="addToCart('book1', 'price1')">Add to cart!</button>
</td>
<!-- Create the shopping cart area of the page-->
<td rowspan="10">
<!-- Create the space for the items in the cart to be written -->
<div id="cartItems"></div>
<!-- Create the space for the Total Price to be written -->
<b>Total Price: $<div style="display: inline" id="totalPrice">0</div></b>
</td>
</tr>
エントリの削除以外はすべて機能します。特に、削除する必要がある特定のノードにアクセスする方法を理解するのに苦労しています。上に示した人工知能の書籍のショッピング カート内のエントリはすべて同じ ID (「book1」) で作成されているため、1 つを選択する方法がわかりません。
前もって感謝します。