我想在选中复选框时为当前价格指定新值。 我的代码是:
var price = 10;
var item = $(".item");
var total = $(".total");
$(".item").change(function() {
price += item.val(); // not working
// price += 10; // not working
// alert('debug'); //work
});
// if i add outside change block work perfect
// price += 10 // work
total.text(price);
<input type="checkbox" value="1" class="item">
<div class="total"></div>
在price
区块内,change
的价值未发生变化?我做错了什么?
答案 0 :(得分:0)
您有一些问题正在发生。
+
来完成的。javascript应如下所示:
// Document ready - wait until all elements are loaded before binding
jQuery(function($) {
var price = 10;
// Assign this INSIDE the document ready
var total = $(".total");
// Bind events INSIDE document ready
$(".item").change(function() {
// When this was outside, you could only have ONE "item"
var item = $(this);
// Only add if checked
if (item.is(":checked")) {
// the +item.val() "casts" the value as a number
price += +item.val();
} else {
price -= +item.val();
}
// Update the total value
total.text(price);
});
// Put the total value in on initial load
total.text(price);
});