在不知道特定ID的情况下获取data- *的值

时间:2019-01-14 12:14:32

标签: jquery html

我有一个带有名称价格为data的html标签。

$('input:radio[name="optradio"]').change(function() {
  var selectedText = $(this).closest('.radio-inline').text();
  var selectedCapacity = $(this).attr('data-capaciteit');
  var selectedPrice = $(this).closest('.bb').attr('data-price');
  console.log('Selected Text ', selectedText);
  console.log('Selected Capacity ', selectedCapacity);
  console.log('Selected Price ', selectedPrice);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='clearfix gbo' id='bike_economy' data-capaciteit='economy bike'>
  <div style='float: left;' class='bb'><img class='tic' src=''></div>
  <div style='float: left;' class='economy'>Economy</div>
  <div style='float: right;' class='infuhr'>
    <ion-icon class='ic' name='information-circle-outline' data-toggle='tooltip' data-placement='right' title='lorem ipsum'></ion-icon>
  </div>
  <div style='float: right;' class='bb transport_amount'><span class='bb' id='economy_bike_amount' data-price='400'>Ksh 250</span>
    <br/> <span class='pt' id='economy_bike_pt'>Pickup by 00:00 pm</span></div>
  <div class='typesd'>
    <label class='radio-inline'>
                <input type='radio' name='optradio' value='any' data-capaciteit='economy' checked>Any</label>
    <label class='radio-inline'>
                <input type='radio' name='optradio' value='box' data-capaciteit='economy'>Box</label>
    <label class='radio-inline'>
                <input type='radio' name='optradio' value='no box' data-capaciteit='economy'>No&nbsp;Box</label>
  </div>
</div>

这是小提琴http://jsfiddle.net/9foqat3k/3/

单击单选按钮时,我有兴趣阅读<span class='bb' id='economy_bike_amount' data-price='400'>Ksh 250</span>

此行var selectedPrice = $(this).closest('.bb').attr('data-price');给出undefined。在不知道跨度的id的情况下如何查看价格?

1 个答案:

答案 0 :(得分:1)

indexed = 0仅在祖先中搜索。

相反,请使用:

.closest()

var selectedPrice = $(this).closest('.gbo').find('.transport_amount .bb').data('price');
$('input:radio[name="optradio"]').change(function() {
  var selectedText = $(this).closest('.radio-inline').text();
  var selectedCapacity = $(this).data('capaciteit');
  var selectedPrice = $(this).closest('.gbo').find('.transport_amount .bb').data('price');
  console.log('Selected Text ', selectedText);
  console.log('Selected Capacity ', selectedCapacity);
  console.log('Selected Price ', selectedPrice);
});