我得到了以下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之后插入一些东西。任何想法如何解决?
谢谢。
答案 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');
<强>演示:强>
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;
您可以像这样更新您的代码:
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>