简体   繁体   English

jQuery将数据属性传递给回调函数

[英]jquery pass a data-attribute to a callback function

Hey guys I have the following function where obj is a table row 大家好,我有以下功能,其中obj是表行

calculate: function(obj) {     
  var sum = 0;   
  $('option:selected', obj).attr('value', function(i,v){
    sum += Number(v);
  });
  $('td:last', obj).text(sum);
  HoursSum.table.trigger('sumChanged', sum);
}

At this point it is correctly retrieving the value attribute. 此时,它正在正确检索value属性。 My question is: How can I access a data attribute of the same selected option? 我的问题是:如何访问相同选择选项的data属性? I have tried: 我努力了:

 ('option:selected', obj).data('duration', ....
.data('data-duration')
.attr('duration') 

However none of them seem to work. 但是,它们似乎都不起作用。 The jQuery documentation says that data() should do the trick but in this case for some reason it doesn't. jQuery文档说data()应该可以解决问题,但是在这种情况下出于某种原因,它就没有作用。 Any ideas? 有任何想法吗?

Example HTML HTML范例

<td class='col-sm-1' style='background-color:pink'>
  <select id='22505.30' class='form-control-sm' style='font-size: 11px;' name='shifts' onchange="submitEntry(this.value,this.id, 22505, '30.06.2018')">
    <option value='0'>Select</option>
    <option data-duration='10.60' data-shiftstart='21:00' data-shiftend='06:00' value='120'>test</option>
    <option data-duration='1.00' data-shiftstart='12:00' data-shiftend='13:00' value='118'>test1</option>
  </select>
</td>

You can try the following code. 您可以尝试以下代码。 but we need to see your HTML to help you with better code. 但是我们需要查看您的HTML以帮助您编写更好的代码。

calculate: function(obj) {     
  var sum = 0;   
  $('option:selected', obj).each(function(){
    var data = $(this).data();
    sum += data.duration;
  });
  $('td:last', obj).text(sum);
  HoursSum.table.trigger('sumChanged', sum);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM