<div style="margin: 5% 2.5% 5% 2.5%; margin-top: 7px; background-color: green; height: 90%; line-height: 35px; color: white; font-size: 14px" class="add" name="0" price="15"><strong class="temp">添加</strong></div>
$(".add").click(function () {
if ($(this).attr('name') == "0") {
$(this).attr('name', "1");
$(this).css("background-color", "gray");
$(this).children(".temp").html("取消");
//计算总价
var a = parseFloat($(".price").text());
a = a + parseFloat($(this).attr('price'));
$(".price").html(a);
}
else
{
$(this).attr('name', "0");//name的值做标记
$(this).css("background-color", "green");
$(this).children(".temp").html("添加");
//计算总价
var a = parseFloat($(".price").text());
a = a - parseFloat($(this).attr('price'));
$(".price").html(a);
}
});
$(this).attr('name');获取当前那个节点里面的name的值
$(this).attr('name',"123");给当前那个节点里面的name的赋值为 123
$(this)=====>好用!!
<div style="margin: 5% 2.5% 5% 2.5%; margin-top: 7px; background-color: green; height: 90%; line-height: 35px; color: white; font-size: 14px" ><strong class="cut" class="add" name="0" price="15">- </strong><span class="count">0</span><strong class="add" class="add" name="0" price="15"> +</strong></div>
$(".add").click(function () {
$(this).prev(".count").html("222");
//计算总价
var a = parseFloat($(".price").text());
a = a + parseFloat($(this).attr('price'));
$(".price").html(a);
});
这里面有几个主要的点:
1 this的用法
2 在this里面获取同级节点,父结点 子节点
$(this).prev(".count").html("222");
他的意思是查找这个 add 的同级(前面位置 class为 count的)节点
$(this).next(".count").html("222");
他的意思是查找这个 add 的同级(后面位置 class为 count的)节点