2012-07-07 46 views
1

我正在使用具有圖像而不是文本(使用css的背景)的選擇框。if else else with a select box的值(純javascript)

<script type="text/javascript"> 
function onChange(element) { 
element.style.backgroundColor = "Yellow"; 
element.className = "on_change"; 
} 
</script> 



<select onchange="onChange(this);"> 
<option value="1" style="background: url(/one.png) no-repeat scroll 0 0 transparent; width:32px; height:32px;"></option> 
<option value="2" style="background: url(/two.png) no-repeat scroll 0 0 transparent; width:32px; height:32px;"></option> 
<option value="3" style="background: url(/three.png) no-repeat scroll 0 0 transparent; width:32px; height:32px;"></option> 
</select> 

的問題是如何獲取所選擇的選項的值,如果是1設置一個圖片,如果它是兩個設置的另一個圖像使用純JavaScript(jQuery的無)的背景是什麼?

我知道selectedIndex是我的問題的關鍵,但我不知道如何使用它或如何在if else語句中使用它。

上面的腳本只是我的一個試驗,我實際上使用上面的腳本來執行相同的任務。

<select onchange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor; this.style.color=this.options[this.selectedIndex].style.color"> 

回答

1

這裏是工作示例。 http://codebins.com/codes/home/4ldqpb9

你不需要if else,只是改變基於selectedIndex的背景圖像。

function onChange(obj) { 
    obj.style.backgroundImage = obj.options[obj.selectedIndex].style.backgroundImage 
} 
+0

嗨,謝謝,只是一件事,圖像重複,所以我用'background'替換'backgroundImage'這是正確的嗎? – user983248 2012-07-07 03:26:20

+0

.background不會有問題。但我建議你寫CSS,以免重複。像「選擇,選擇選項{背景 - 重複:不重複;}」並且只有背景圖像的樣式標記。所以你有一點清潔標記 – gaurang171 2012-07-07 03:55:15

+0

Greaat!不幸的是,我只是發現,它不會在IE瀏覽器上工作,所以現在試圖找到一個解決方案 – user983248 2012-07-07 07:46:41