2010-02-08 50 views
1

我想加載選項下拉列表取決於在其他下拉列表中所做的選擇。我已經編寫了幾乎適用於所有主流瀏覽器的代碼,FF,Opera,Safari,但在IE7中無法使用。爲什麼這個JavaScript事件不適用於IE ..?

這裏是我的Javascript代碼:

<script type = "text/javascript"> 
var txt1 = "<option>state1<\/option><option>state2<\/option><option>state3<\/option><option>state4<\/option>"; 
var txt2 = "<option>stateA<\/option><option>stateB<\/option><option>stateC<\/option><option>stateD<\/option><option>stateE<\/option>"; 

function states_val() { 

    if(document.getElementById("country").options[0].selected==true) { 
     document.getElementById("states").disabled=true; 
     document.getElementById("states").innerHTML="<option>Select country<\/option>"; 
    } 
    else if(document.getElementById("country").options[1].selected==true) { 
     document.getElementById("states").disabled=false; 
     document.getElementById("states").innerHTML=txt1; 
    } 
    else if(document.getElementById("country").options[2].selected==true) { 
     document.getElementById("states").disabled=false; 
     document.getElementById("states").innerHTML=txt2; 
    } 
} 
</script> 

和HTML代碼:

<select id="country" name="name_country" onchange="states_val()"> 
    <option>select</option> 
    <option>country1</option> 
    <option>country2</option> 
</select> 
<select id="states" name="name_states"></select> 

我一定與客戶端腳本,並有只模擬這種使用Javascript。請幫我調試代碼。

+0

在快看,我看不出有什麼毛病腳本。難道你期待* onchange *事件立即被觸發,而事實上它只有在控件失去焦點時纔會被觸發(你點擊/選擇除下拉框以外的任何東西)。 – 2010-02-08 13:37:01

+0

@miguel,對不起,我沒有明白你的意思。 – user268533 2010-02-08 14:00:26

+0

@miguel,以及我的要求,正如我所提到的,需要改變一個選擇元素的選項值取決於其他。 – user268533 2010-02-08 14:01:34

回答

7

是的,許多「特殊」元素,如<select><table>不能在IE中設置它們的innerHTML

如果你想設置從字符串innerHTML你必須去了解它以一種迂迴的方式:設置臨時div元素innerHTML<select> +您的選擇+ </select>,那麼所有的選項對象移動距離新選擇舊的。

這是一般最好使用DOM方法而不是innerHTML逃到標記:

function setOptions(select, options) { 
    select.options.length= 0; 
    for (var i= 0; i<options.length; i++) 
     select.options[i]= new Option(options[i]); 
} 

var statemap= [ 
    ['Select country'], 
    ['Karnataka', 'MP', 'UP', 'Jammu & Kashmir', 'Himachal Pradesh'], 
    ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Delaware', 'Florida'] 
]; 
function states_val() { 
    var states= statemap[document.getElementById('country').selectedIndex]; 
    setOptions(document.getElementById('states'), states); 
} 
+0

。 – user268533 2010-02-08 13:59:24

2

我認爲這是一個確認的錯誤(http://alexle.net/archives/150)的解決辦法是更換整個選擇的元素,而不僅僅是的innerHTML(選項..)

另外,您可以手動創建選項節點與

var anOption = document.createElement('option'); 
anOption.innerHTML = '..'; 
anOption.value = '..'; 
document.getElementByID('states').appendChild(anOption); 
+0

好的。 thanx的信息。發佈100%工作解決方案時,thanx爲 – user268533 2010-02-08 13:58:55

相關問題