属性名称使用 jQuery 获取值
attribute name get value with jQuery
我有这个代码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属性的值?
我尝试了以下代码,但没有 return 任何东西:
val_id_template = $('#id_select').append().attr("name");
console.log(val_id_template);
谢谢!
删除 append()
并尝试。当您使用 $('#id_select option:selected')
:
时,它将为您提供 select
列表中所选 option
的 name
值
val_id_template = $('#id_select option:selected').attr("name");
console.log(val_id_template);
<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>
或者,如果您想在从列表中选择 option
时获取 name
的值,则:
$('#id_select').change(function(){
console.log($('#id_select option:selected').attr('name'));
});
<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>
我有这个代码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属性的值? 我尝试了以下代码,但没有 return 任何东西:
val_id_template = $('#id_select').append().attr("name");
console.log(val_id_template);
谢谢!
删除 append()
并尝试。当您使用 $('#id_select option:selected')
:
select
列表中所选 option
的 name
值
val_id_template = $('#id_select option:selected').attr("name");
console.log(val_id_template);
<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>
或者,如果您想在从列表中选择 option
时获取 name
的值,则:
$('#id_select').change(function(){
console.log($('#id_select option:selected').attr('name'));
});
<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>