2

重複の可能性:
選択リストで JavaScript を使用して作成された属性を使用する

選択リストで作成した属性にアクセスしようとしています。

<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>

それは私にnullを与え続けます。属性 car から値を取得するにはどうすればよいですか?

4

2 に答える 2

6

選択したオプションの属性から値を取得する場合car:

//get the option's car attribute at selectedIndex
var car = document.getElementById('test').options[select.selectedIndex].car;
于 2012-04-29T04:47:09.720 に答える
5

この属性は選択されていません。それは最初のオプションにあります:

document.getElementById('test').options[0].getAttribute('car')
于 2012-04-29T04:43:24.917 に答える