2010-10-12 47 views
2

場的名字,我有兩套稱爲state_d列表(國家列表) 一位名爲STATE_O和一個和我有一個功能,我對他們現在要做的獲取傳遞

function selectCountry(sel) { 
    document.getElementById("country_o").selectedIndex = states[sel.value]; 
} 

我想要做的是確定「sel」是否爲state_o或state_d並根據選擇的狀態將getElementById(「country_o」)更改爲_o或_d,因此state_o會執行country_o和state_d將執行country_d

如何確定選擇字段名稱?

謝謝!

回答

2

您可以通過JavaScript訪問name屬性:

function selectCountry(sel) { 
    var od = sel.name == "state_o" ? "o" : "d"; 
    document.getElementById("country_"+od).selectedIndex = states[sel.value]; 
} 

或者,如果你想成爲一個有點票友,並保持它在同一行,切片O/d直接從名稱字符串:

function selectCountry(sel) { 
    document.getElementById("country_"+sel.name.slice(-1)).selectedIndex = states[sel.value]; 
} 
+0

+1 Nice clean function update。 – 2010-10-12 17:52:35

0

在此函數中保留另一個參數,以查看它的_o或_d並在調用函數中設置此值。 然後,在JavaScript方法,你可以通過撥打國家 -

document.getElementById("country" + param2) 

假設參數2是附加參數,它將包含字符串「_o」或「_d」

-1

使用sel.attr('name')如果你正在使用jQuery或sel.name如果只是使用普通的舊的Javascript

假設你有:

<SELECT name='state_o'> 
    <OPTION value='blah'>BLAH</OPTION> 
</SELECT> 
<SELECT name='state_d'> 
    <OPTION value='blah'>BLAH</OPTION> 
</SELECT> 
+0

* attr()*不是任何DOM對象上的有效函數。 – 2010-10-12 17:54:36

+0

$(sel),attr(「name」)應該這樣做 – 2010-10-12 19:36:32

0

如果我明白你的問題的權利,它只是:

var field; 
if (sel.value == 'state_o') 
    field = 'country_o'; 
else 
    field = 'country_d'; 

document.getElementById(field).selectedIndex = states[sel.value]; 
0

如果sel是選擇元素,sel.idsel.name應該給你你想要的東西。

相關問題