【发布时间】:2016-01-31 07:58:35
【问题描述】:
我正在创建一个简单的 jQuery 购物清单作为我的第一个 jQuery 项目。我正在动态添加每个项目,并允许用户传递估计成本的价格。当每个项目都添加到列表中时,我会显示总估计成本。
如果用户想要删除一个项目,我想删除该项目并更新总成本。这是我添加带有成本的项目的代码...
//Append individual ITEM and individual PRICE to document
var addToList = '<li class="addedItem">' +addItem+
'<span> will cost you $</span>' +addPrice+
'<button class="delete">Delete</button></li>';
$('#items').append(addToList);
我怎样才能只选择要删除的项目的附加价格,以便相应地减去总价?
$(document).ready(function() {
//Stop the form from submitting
$('#submit-form').submit(function(e) {
e.preventDefault();
});
//Variables to store totals
var itemCounter = 0;
var priceCounter = 0;
//Handler to get value of ITEM and PRICE
$('#submit-btn').click(function() {
//Get value for submitted item and append to list
var addItem = $('#item').val();
itemCounter++;
//Functionality to keep track of TOTAL PRICE and be able to remove an
//item so the price reflects the removal
var addPrice = Number.parseInt($('#cost').val());
alert(typeof(addPrice));
priceCounter += addPrice;
//Append ITEM and PRICE to document
var addToList = '<li class="addedItem">' + addItem + '<span> will cost you $</span>' + addPrice + '<button class="delete">Delete</button></li>';
$('#items').append(addToList);
//Clear the form after submit
$('#item').val('');
$('#cost').val('');
//Clear ESTIMATED COST TOTAL and append new total
$('#estimatedCost').html('');
$('#estimatedCost').append(priceCounter);
//Appends totals to TOTALS
//HTML to append
$('#itemsTotal').html('');
$('#itemsTotal').append(itemCounter);
});
//Functionality for Delete Button
$(document).on('click', '.delete', function() { //Because the delete button has been created
//dynamically you must specify
$(this).parent().remove(); //to listen to the DOCUMENT for the click on 'DELETE'
$(this).remove();
alert($(this).prev().val());
$('#estimatedCost').append(priceCounter);
});
//Function to create sum all off prices
function sumPrice() {}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<title>Let's Go Shopping!</title>
<link rel='stylesheet' href='css/style.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='js/script.js'></script>
</head>
<body>
<header>
<h4>A handy app to keep your spending on track!</h4>
</header>
<div class='main-form'>
<form id='submit-form' name='submit-form'>
<!-- Form submit for ITEM -->
<input type='text' id='item' placeholder="What Should I Get?">
<input type='number' value='number' id='cost' placeholder="Estimated Cost"><br>
<input type='submit' name='submit-btn' id='submit-btn' value="Let's get it!">
</form>
</div>
<section id='list'>
<ul id='items'></ul>
<div id='totals'>
<div><h3>Items to Buy</h3></div>
<div id='itemsTotal'></div>
</div>
<div><h3>Esitmated Cost</h3></div>
<div id='estimatedCost'></div>
</section>
</body>
</html>
【问题讨论】:
标签: javascript jquery