在多选中获取自定义属性值

Get custom attribute value in multiple select

本文关键字:自定义属性 获取      更新时间:2023-09-26

我有很多像下面这样的选择元素,当选择任何选项时我需要得到data-cal的值

  <select data-cal="89" name="caloriecalculator" style="width: 100px;">
                      <option value="100">Per 100g</option>
                      <option value="225">1 cup, mashed </option>
                      <option value="150">1 cup, sliced </option>
    </select>
    <select data-cal="109" name="caloriecalculator" style="width: 100px;">
                      <option value="100">Per 100g</option>
                      <option value="225">1 cup</option>
                      <option value="150">1 cup big</option>
    </select>

我的查询代码

$('select[name="caloriecalculator"]').change(function() {
//I need to get the data atribute (data-cal) of select here.
});

你可以使用 $.data 方法,像这样

$('select[name="caloriecalculator"]').change(function() {
  console.log($(this).data('cal') );
});

演示:http://jsbin.com/letoje/1/edit?html,js,output

你试过吗:

$('select[name="caloriecalculator"]').change(function() {
    var cal = $(this).data('cal');
});