Javascript从表中的选定选项获取数据属性

时间:2017-06-05 13:22:53

标签: javascript jquery

我得到了以下HTML:

<td class="" data-id="46" contenteditable="true">
<select class="form-control">
   <option data-key="end" selected>Opt1</option>
   <option data-key="operator_transfer">Opt2</option>
   <option data-key="process_script">Opt3</option>
</select>
</td>

我需要获取所选选项的数据属性。我试着这样做:

var cell = $row.find(':nth-child(4)');
dataattr = cell[0].getAttribute('data-id');
var selectObject = cell.find("select");
if(selectObject.length){// if it is a select
    localobj[dataattr] = selectObject[0].getAttribute('data-key');//val(); previously it was val() here but now I want data-key
}

我试过这个:

$(selectObject/*need to insert something here*/ + ' option:selected').data('key');

但它显示一个错误,说它是一个对象Object。我需要在selectObject之后插入一些东西。任何想法如何解决?

谢谢。

3 个答案:

答案 0 :(得分:2)

使用jquery函数attr()

尝试此$('.form-control').children('option:selected').attr('data-key')

console.log($('.form-control').children('option:selected').attr('data-key'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="" data-id="46" contenteditable="true">
<select class="form-control">
   <option data-key="end" selected>Opt1</option>
   <option data-key="operator_transfer">Opt2</option>
   <option data-key="process_script">Opt3</option>
</select>
</td>

对于您的代码,您可以这样做

var cell = $row.find(':nth-child(4)');
dataattr = cell[0].getAttribute('data-id');
var selectObject = cell.find("select");
if(selectObject.length){// if it is a select
    localobj[dataattr] = selectObject[0].getAttribute('data-key');
}
$(selectObject).children('option:selected').data('key');

答案 1 :(得分:0)

您只需要使用正确的选择器jQuery data()方法,如下所示:

$('select option:selected').data('key');

<强>演示:

&#13;
&#13;
var key = $('select option:selected').data('key');
console.log(key);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="" data-id="46" contenteditable="true">
<select class="form-control">
   <option data-key="end" selected>Opt1</option>
   <option data-key="operator_transfer">Opt2</option>
   <option data-key="process_script">Opt3</option>
</select>
</td>
&#13;
&#13;
&#13;

您可以像这样更新您的代码:

if (selectObject.length) { // if it is a select
  localobj[dataattr] = selectObject[0].getAttribute('data-key');
}
$(selectObject).find('option:selected').data('key');

答案 2 :(得分:0)

$('.form-control').change(function(){
alert($('.form-control').find(':selected').attr('data-key'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="" data-id="46" contenteditable="true">
<select class="form-control">
   <option data-key="end" selected>Opt1</option>
   <option data-key="operator_transfer">Opt2</option>
   <option data-key="process_script">Opt3</option>
</select>
</td>