如何选择jQuery的HTML5的数据属性? [英] How to select the HTML5 data attribute in jQuery?

查看:110
本文介绍了如何选择jQuery的HTML5的数据属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前的jQuery选择的价值属性。如何更改我的jQuery选择数据属性数据价?

  $('#trapfabric,#trapsize')。在('变化',函数(){
  变量$ =选择$('#trapfabric,#trapsize')儿童(:选择了)。
  总和= parseInt函数($('#trapsize)VAL())+ parseInt函数($('#trapfabric)VAL());
  $('#priceToSwap3')。HTML('$'+总和
    );
});

我知道我必须适应在上述这样的事情,但我不能得到它的工作:

  $('#priceToSwap3')。文本($ selected.data(价格))

EDITED

我的HTML:

 <跨度ID =priceToSwap3> $ 238 LT; / SPAN><选择一个id =trapsize的onChange =swapImage()>
 <选项数据价=238>富< /选项>
 <选项数据价=288>富< /选项>
< /选择><选择一个id =trapfabric的onChange =swapImage()>
 <选项数据价=0>富< /选项>
 <选项数据价=20>富< /选项>
< /选择>


解决方案

我相信这是你想要什么:

 变量$ =元素$('#trapfabric,#trapsize');
$ elements.on('变',函数(){
     变量$选择= $ elements.children(:选择);
     变种总和= 0;     $ selected.each(函数(){
         总和+ = $(本)。数据(价格);
     });     $('#priceToSwap3')HTML('$'+总和);
});

您必须遍历所选元素,以获得价格他们每个人的数据。

DEMO

My current jQuery selects the value attribute. How do I change my jQuery to select the data attribute "data-price"?

$('#trapfabric, #trapsize').on('change', function() {
  var $selected = $('#trapfabric, #trapsize').children(":selected");
  sum = parseInt($('#trapsize').val()) + parseInt($('#trapfabric').val());
  $('#priceToSwap3').html('$' + sum
    );
});

I know I have to fit something like this in the above but I can't get it to work:

$('#priceToSwap3').text($selected.data("price"))

EDITED

My HTML:

<span id="priceToSwap3"">$238</span>

<select id="trapsize" onChange="swapImage()">
 <option data-price="238">foo</option>
 <option data-price="288">foo</option>
</select>

<select id="trapfabric" onChange="swapImage()">
 <option data-price="0">foo</option>
 <option data-price="20">foo</option>
</select>

解决方案

I believe this is what you want:

var $elements = $('#trapfabric, #trapsize');
$elements.on('change', function() {
     var $selected = $elements.children(":selected");
     var sum = 0;

     $selected.each(function() {
         sum += $(this).data('price');
     });

     $('#priceToSwap3').html('$' + sum);
});

You have to iterate over the selected elements to get the price datum of each of them.

DEMO

这篇关于如何选择jQuery的HTML5的数据属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆