我有这个代码html:
<select id='id_select'>
<option name='nm_opt' value='23'>Val1</option>
<option name='nm_opt2' value='16'>Val2</option>
<option name='nm_opt' value='6'>Val3</option>
</select>
如何使用jQuery获取name属性的值? 我尝试了以下代码,但没有返回任何内容:
val_id_template = $('#id_select').append().attr("name");
console.log(val_id_template);
谢谢!
答案 0 :(得分:4)
删除append()
然后尝试。当您使用name
时,它会为option
列表中的所选select
提供$('#id_select option:selected')
值:
val_id_template = $('#id_select option:selected').attr("name");
console.log(val_id_template);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='id_select'>
<option name='nm_opt' value='23'>Val1</option>
<option name='nm_opt2' value='16'>Val2</option>
<option name='nm_opt' value='6'>Val3</option>
</select>
&#13;
或者如果您想从列表中选择name
时获得option
的值,那么:
$('#id_select').change(function(){
console.log($('#id_select option:selected').attr('name'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='id_select'>
<option name='nm_opt' value='23'>Val1</option>
<option name='nm_opt2' value='16'>Val2</option>
<option name='nm_opt' value='6'>Val3</option>
</select>
&#13;