数据属性的总和

Yun*_*ork 3 javascript jquery

如何在jquery中获取HTML5数据属性的总和?例如,当检查一个和两个时,值必须为15,当没有检查时,值等于0.

$('.price').html(parseInt($(this).attr('data-price')));
Run Code Online (Sandbox Code Playgroud)

HTML:

<input class="checkbox" id="one" type="checkbox" checked data-link="111" data-price="10">one<br />
<input class="checkbox" id="two" type="checkbox" checked data-link="222" data-price="5">two<br />
<input class="checkbox" id="three" type="checkbox" checked data-link="333" data-price="2">three<br />
<a href="111,222,333">link</a>
<span class="price">17</span>
Run Code Online (Sandbox Code Playgroud)

javascipt的:

$('.checkbox').on("change", function() {
    var links = [];//array for links
    $('.checkbox').filter(":checked").each(function() {
        links.push($(this).attr('data-link'));//get links

        //sum of all price values of this into price
        $('.price').html(parseInt($(this).attr('data-price')));
    });

    $("a").attr("href", links.join(",")); // change link
});
Run Code Online (Sandbox Code Playgroud)

小提琴

Ror*_*san 7

您需要修改代码,以便在循环的每次迭代之间保持运行总计.试试这个:

$('.checkbox').on("change", function () {
    var links = []; //array for links
    var totalPrice = 0;

    $('.checkbox:checked').each(function () {
        links.push($(this).data('link')); //get links
        totalPrice += $(this).data('price');
    });

    $('.price').html(totalPrice);
    $("a").attr("href", links.join(",")); // change link
});
Run Code Online (Sandbox Code Playgroud)

示例小提琴

请注意,它也可以更快地使用data()而不是attr('data-x')

  • 使用[`.data()`](https://api.jquery.com/data/#data-key)时,不需要对数字数据属性使用`parseInt`:_"每次尝试都是将字符串转换为JavaScript值(包括布尔值,数字,对象,数组和null)."_ (2认同)