我想通过单击像 div class box2 这样的项目将项目添加到购物车我有演示项目当我单击图像时我得到名称和价格但名称和价格没有添加到 ul 类添加请帮我看看如何从图像中获取值并将其放入购物车
<div class="box2">
<p>pkr 700.0</p>
<img src="images/col.png" />
<h1>Beverges</h1>
</div>
<ul class="add">
<li>bellle belle belle 25cl
<p>2 Unit(s) at PKR 0.8/Unit(s)</p>
</li>
</ul>
<script type="text/javascript">
$(document).ready(function() {
$('.box2').click(function(){
var price=$(".box2 p:first").html();
var product=$(".box2 h1:first").html();
$(".add li:first").val(product);
$(".add li p:first").val(price);
alert(price);
alert(product);
});
});
</script>
最佳答案
使用text method或 html method而不是 val 方法:
$(".add li:first").text(product);
$(".add li p:first").text(price);
或者,
$(".add li:first").html(product);
$(".add li p:first").html(price);
val() 方法仅适用于输入元素类型。
您正在为将覆盖的同一元素分配两个值,因此请像这样使用:
$(".add li:first").text(product + " " + price);
更新:根据评论demo
$('.box2').click(function(){
var price=$(".box2 p:first").html();
var product=$(".box2 h1:first").html();
$(".add li:first").contents().filter(function(){
return this.nodeType == 3;
})[0].nodeValue = product;
$(".add li:first p").text(price);
});
关于javascript - 通过 jquery 向购物车添加值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22656685/