用HTML+CSS和jq写简易购物车代码?

用HTML+CSS和jq写简易购物车代码?,第1张

以下是一个简易购物车的HTML+CSS和jQuery代码示例:

HTML部分:

<div class="cart-container">

<h2>购物车</h2>

<ul class="cart-items">

<li class="cart-item">

<img src="item1.jpg" alt="商品1">

<span class="item-name">商品1</span>

<span class="item-price">100元</span>

<input type="number" class="item-quantity" value="1">

<button class="remove-btn">删除</button>

</li>

<li class="cart-item">

<img src="item2.jpg" alt="商品2">

<span class="item-name">商品2</span>

<span class="item-price">200元</span>

<input type="number" class="item-quantity" value="1">

<button class="remove-btn">删除</button>

</li>

</ul>

<p class="total-price">总价:<span>300元</span></p>

</div>

CSS部分:

.cart-container {

width: 400px

border: 1px solid #ccc

padding: 20px

}

.cart-items {

list-style-type: none

padding: 0

margin: 0

}

.cart-item {

display: flex

align-items: center

margin-bottom: 10px

}

.cart-item img {

width: 80px

height: 80px

margin-right: 10px

}

.item-name, .item-price {

flex: 1

}

.item-quantity {

width: 50px

margin-right: 10px

}

.remove-btn {

background-color: #ccc

border: none

padding: 5px 10px

cursor: pointer

}

.total-price {

margin-top: 20px

text-align: right

}

jQuery部分:

$(document).ready(function() {

// 计算初始总价

updateTotalPrice()

// 删除商品按钮点击事件

$('.remove-btn').click(function() {

$(this).parent().remove()

updateTotalPrice()

})

// 商品数量输入框变化事件

$('.item-quantity').change(function() {

updateTotalPrice()

})

// 更新总价函数

function updateTotalPrice() {

var total = 0

$('.cart-item').each(function() {

var price = parseInt($(this).find('.item-price').text())

var quantity = parseInt($(this).find('.item-quantity').val())

total += price * quantity

})

$('.total-price span').text(total + '元')

}

})

该示例中,使用了HTML和CSS来构建购物车的界面,使用jQuery来实现购物车的逻辑。购物车中的每个商品都包含了商品名称、商品图片、商品价格、商品数量和删除按钮,当点击删除按钮时,对应的商品会从购物车中删除并重新计算总价;当商品数量变化时,总价也会自动更新。

<script>

jQuery(function($) {

    $("#add").on("click", function() {

        var boxs = $(":checkbox[name='haitai']:checked")

        if (!boxs.length) {

            alert("请选择商品!")

        } else {

            var bao = ""

            boxs.each(function(i, dom) {

                bao += $(dom).attr("value") + "\n"

            })

            localStorage.car = localStorage.car ? bao + localStorage.car : bao

            alert("成功加入购物车!")

        }

    })

})

</script>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11416218.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-15
下一篇2023-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存