jQuery:在点击时添加属性值

时间:2012-05-06 02:32:21

标签: javascript jquery jquery-selectors

我有电子商务网站。我有产品页面,您可以在主产品中选择不同的变体和插件。 我希望能够在客户点击选项时动态显示价格。

基本的HTML看起来像这样:

<div class="addons">
    <input type="radio" name="products[39][addons][Handles]" title="Handles" value="579" alt="7.00" class="options"> Bronze Left
    <input type="radio" name="products[39][addons][Handles]" title="Handles" value="580" alt="8.00" class="options"> Bronze Right
    <input type="radio" name="products[39][addons][Handles]" title="Handles" value="581" alt="9.00" class="options"> Chrome Left
    <input type="radio" name="products[39][addons][Handles]" title="Handles" value="582" alt="10.00" class="options"> Chrome Right  

    <input type="radio" name="products[39][addons][Glass]" title="Glass" value="589" alt="18.00" class="options"> Brass Clarity
    <input type="radio" name="products[39][addons][Glass]" title="Glass" value="590" alt="20.00" class="options"> Zinc Abstract
    <input type="radio" name="products[39][addons][Glass]" title="Glass" value="591" alt="21.00" class="options"> Zinc Elegance
    <input type="radio" name="products[39][addons][Glass]" title="Glass" value="592" alt="23.00" class="options"> Zinc Prairie  
</div>

Value属性用于添加到购物车功能,我无法更改,价格设置为alt,但显然可以设置任何标题jQuery点击目标。

我需要jQuery的帮助。我遇到的问题是我不知道如何让var价格在点击功能之外相互加起来。

$("input[type='radio'][title='Handles']").click(function() {
    price = $(this).val();
}

$("input[type='radio'][title='Glass']").click(function() {
    price = $(this).val();
}   

4 个答案:

答案 0 :(得分:1)

如果我理解,您只想在 alt 中添加值。你可以这样做:

var total = 0;
$(".addons").find("input:checked").each(function() {
    total += parseFloat($(this).attr('alt'));
});

您可以在点击处理程序中运行此代码,并更新HTML显示的总数。

编辑“输入:已检查”比“输入[已检查=已检查]”更清晰。

答案 1 :(得分:1)

您可以使用input[type='radio']:checked过滤并获取您要查找的元素。

var total = 0;

// Get all the input tags that are checked.
$(".addons").find("input[type='radio']:checked").each(function() {
    total += parseFloat($(this).attr('alt'));
});

答案 2 :(得分:0)

如果我正确理解了这一点,你想要加上每个选定选项的价格。这是一种方法:

// An object to keep track of the total amount of each title
var total = {};

// Change event on the radio buttons
$('input[type=radio]').change(function() {
    // Assign the alt to the total object with the key name being the title
    total[$(this).attr('title')] = parseFloat($(this).attr('alt')).toFixed(2);

    // Output the result to HTML (optional)
    outputTotal();
});

function outputTotal()
{
    // Here all the prices are being summed
    var sum = 0;

    for(var index in total)
    {
        sum += total[index];
    }

    // And output to HTML
    $('.total').html(sum);
}

jsFiddle example

答案 3 :(得分:0)

var inputs = $(".addons input.options");
inputs.click(function() {
    var total = 0;
    $(".addons").find(":checked").each(function(){
       total += parseFloat($(this).attr("alt"));
    });
    $("#total").val(total);
});

http://jsfiddle.net/tive/fyZbV/