Get data-price jquery

2019-09-02 21:12发布

I want to ask how can i sum data-price from images onclick with jquery?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<body>
<img id="1" src="" data-price="5">
<img id ="2" src="" data-price="10">
<div id="sum"></div>
</body>
</html>

thanks in advance.

2条回答
啃猪蹄的小仙女
2楼-- · 2019-09-02 21:14

You can get data-price using .data()

Try this:

$('#1, #2').click(function() {
    alert( $(this).data('price') );
    var sum = parseInt( $('#1').data('price')) + parseInt( $('#2').data('price'));
    alert(sum);
    $('#sum').html(sum);
});

DEMO

查看更多
ら.Afraid
3楼-- · 2019-09-02 21:15

Target the ID of the images, and attach an event handler, then on click, get the data attribute with data()

$('#1, #2').on('click', function() {
    alert( $(this).data('price') );
});

If you somehow need to sum this up in the #sum element, you should ask specifically about that.

EDIT:

and now you did ?

$('#1, #2').on('click', function() {
    var data1 = parseInt( $('#1').data('price') ,10);
    var data2 = parseInt( $('#2').data('price') ,10);

    $('#sum').text(data1 + data2);
});
查看更多
登录 后发表回答