属性名称使用jQuery获取值

时间:2018-03-15 08:57:20

标签: jquery html append attr

我有这个代码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);

谢谢!

1 个答案:

答案 0 :(得分:4)

删除append()然后尝试。当您使用name时,它会为option列表中的所选select提供$('#id_select option:selected')值:

&#13;
&#13;
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;
&#13;
&#13;

或者如果您想从列表中选择name时获得option的值,那么:

&#13;
&#13;
$('#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;
&#13;
&#13;