大家好,我已经在这个脚本上工作了一段时间了,但我就是无法让它正常工作,我可能错过了一个重要的参数来让它正常工作。
我需要计算标签内部的值并将总数加到 HTML 中:
<div class="catProdAttributeItem">
<input type="radio" id="5583116" name="752526">
<span>Ford £19.99</span>
<img src="http://www.breakerlink.com/blog/wp-content/uploads/2014/01/Ford.png">
</div>
<div class="catProdAttributeItem">
<input type="radio" id="5971554" name="752526">
<span>Ferrary £19.99</span>
<img src="http://www.assettocorsa.net/wp-content/uploads/2013/09/logo2.png">
</div>
<br><br>
<span style="display:none;" class="original_price">£0.00</span>
<div class="updated_price" id="show-price">£0.00</div>
这是我的脚本:
$('.catProdAttributeItem img').on("click", function() {
$(this).siblings('input[type=radio]').attr('checked', true);
var original_price = $('.original_price').text().replace(/[^0-9\.]/g, '');
parseFloat(this.original_price);
var warehouse_price = $(this).siblings('.catProdAttributeItem span').text().replace(/[^0-9\.]/g, '');
warehouse_price = parseFloat(warehouse_price);
var total_price = parseFloat(original_price) + parseFloat(warehouse_price);
$('.updated_price').html('£' + total_price.toFixed(2));
})
我只能得到点击 sibling 的结果,请提供一些帮助,非常感谢..
我希望在选择输入时将 .updated_price 上显示的值相加,但它将适用于更广泛的输入集,您可以在其中检查更多输入,并且可以从所有检查的输入中获得结果
最佳答案
您需要每辆车(不是 radio )的复选框。见下文:
$(document).ready(function() {
$('.catProdAttributeItem img').on("click", function() {
// Make checkbox adjustment
$(this).siblings('input:checkbox').click();
});
$(document).on('click', 'input:checkbox', calcTotal);
});
function calcTotal() {
var total_price = 0;
// find all .catProdAttributeItem divs
$(document).find('.catProdAttributeItem').each(function() {
// see if the checkbox is checked to add to the total_price
var $checkbox = $(this).find('input:checkbox');
if ($checkbox.is(':checked')) {
var text = $(this).find('span').html();
total_price += parseFloat(text.replace(/[^0-9\.]/g, ''))
}
});
// finally display the price
$('.updated_price').html('£' + total_price.toFixed(2));
}
.catProdAttributeItem {
width: 300px;
float: left;
display: inline-block;
text-align: center;
}
img {
width: 100px;
height: auto;
}
.updated_price {
clear: both;
margin: 20px 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="catProdAttributeItem">
<input type="checkbox" id="5583116" name="752526">
<span>Ford £19.99</span>
<img src="http://www.breakerlink.com/blog/wp-content/uploads/2014/01/Ford.png">
</div>
<div class="catProdAttributeItem">
<input type="checkbox" id="5971554" name="752526">
<span>Ferrary £19.99</span>
<img src="http://www.assettocorsa.net/wp-content/uploads/2013/09/logo2.png">
</div>
<br>
<br>
<div class="updated_price" id="show-price">£0.00</div>
关于javascript - 使用 jQuery 将 sibling 的值相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28732438/