在选择列表中使用 javascript 获取属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10369727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:04:11  来源:igfitidea点击:

get attribute value with javascript in select list

javascript

提问by user1241962

Possible Duplicate:
Use created attribute with javascript in select list

可能的重复:
在选择列表中使用带有 javascript 的创建属性

im trying to access an attribute that i created in a select list.

我试图访问我在选择列表中创建的属性。

<script language="JavaScript">
function updateUrl()
    {
        var newUrl = document.getElementById('test').getAttribute('car');
        alert(newUrl);
    }
</script>

<select name= "test" id= "test" onChange= "updateUrl()">
     <option value="1" selected="selected" car="red">1</option> 
     <option value="2" car="blue" >2</option> 
     <option value="3" car="white" >3</option> 
     <option value="4" car="black" >4</option>    
</select>

it keep giving me null. how do i get the value from attribute car?

它一直给我空。我如何从属性汽车中获取价值?

回答by Joseph

If you meant get the value from the carattribute of the selected option:

如果您的意思是从car所选选项的属性中获取值:

//get the option's car attribute at selectedIndex
var car = document.getElementById('test').options[select.selectedIndex].car;

回答by Sampson

This attribute isn't on the select. It's on the first option:

此属性不在选择中。这是第一个选项:

document.getElementById('test').options[0].getAttribute('car')