我遇到了一些问题,如果id="paysms"的复选框被选中,那么如何提高id="value"的所有元素的和,否则为默认值。
这是代码。
<table class='table'>
<tr>
<th width='80%'>some things</th>
<th width='20%'>price (usd)</th>
</tr>
<tr>
<td width='80%'>thing1</td>
<td width='20%' id='value'>1.00</td>
</tr>
<tr>
<td width='80%'>thing2</td>
<td width='20%' id='value'>2.00</td>
</tr>
<tr>
<td width='80%'>thing3</td>
<td width='20%' id='value'>3.00</td>
</tr>
<tr>
<td width='80%'>thing4</td>
<td width='20%' id='value'>15.00</td>
</tr>
<tr>
<td width='80%' style='border: none; background: none;'></td>
<td width='20%'><label><input id='paysms' type='checkbox'> sms</label></td>
</tr>
</table>
undefined的答案似乎并没有达到你想要的效果(据我所知)。我想你现在已经明白了,ID必须是唯一的,所以这里有javascript:
$('#paysms').change(function() {
if ($(this).is(":checked")) {
$(".value").each(function() {
$(this).html(parseInt($(this).html()) + 1 + ".00");
});
} else {
$(".value").each(function() {
$(this).html(parseInt($(this).html()) - 1 + ".00");
});
}
});
和小提琴:http://jsfiddle.net/EwEZK/3/
但是,如果您希望使用除.00以外的十进制值,则需要对其进行修改。
ID必须是唯一,您应该使用类,尝试以下操作:
<table class='table'>
<tr>
<th width='80%'>some things</th>
<th width='20%'>price (usd)</th>
</tr>
<tr>
<td width='80%'>thing1</td>
<td width='20%' class='value'>1.00</td>
</tr>
<tr>
<td width='80%'>thing2</td>
<td width='20%' class='value'>2.00</td>
</tr>
<tr>
<td width='80%'>thing3</td>
<td width='20%' class='value'>3.00</td>
</tr>
<tr>
<td width='80%'>thing4</td>
<td width='20%' class='value'>15.00</td>
</tr>
<tr>
<td width='80%' style='border: none; background: none;'></td>
<td width='20%'><label><input id='paysms' type='checkbox'> sms</label></td>
</tr>
</table>
<p id='result'><p>
jQuery:
$('#paysms').change(function() {
if (this.checked) {
var vals = 0;
$('.value').each(function() {
vals += parseInt($(this).text(), 10)
})
$('#result').text(vals)
} else {
$('#result').text("")
}
})
Fiddle
将id='value'
更改为class='value'
。
$(document).ready(function(){
var price = 0; //default value
$('#paysms').change(function(){
if ($(this).is(':checked')){
$('.value').each(function(){
price += parseFloat($(this).html());
});
} else {
price = 0; // back to default
}
});
});