2012-06-20 41 views
1

總的noob這裏與JavaScript。我試圖改變一個功能。這是目前在那裏工作的那個。javascript noob。變量和元素

function hideStateField(theForm) { 
    theForm.state.disabled = true; 
    theForm.state.className = 'hiddenField'; 
    theForm.state.setAttribute('className', 'hiddenField'); 
    document.getElementById("stateLabel").className = 'hiddenField'; 
    document.getElementById("stateLabel").setAttribute('className', 'hiddenField'); 
    document.getElementById("stateText").className = 'hiddenField'; 
    document.getElementById("stateText").setAttribute('className', 'hiddenField'); 
    document.getElementById("stateBreak").className = 'hiddenField'; 
    document.getElementById("stateBreak").setAttribute('className', 'hiddenField'); 
} 

我想使它更通用,所以它不是特定於「狀態」字段。所以我正在改變函數名來反映並添加第二個參數。然後我試圖用第二個參數作爲變量來代替我們看到「狀態」的地方。

function hideAddressField(theForm,theField) { 
    theForm.theField.disabled = true; 
    theForm.theField.className = 'hiddenField'; 
    theForm.theField.setAttribute('className', 'hiddenField'); 
    document.getElementById(theField+"Label").className = 'hiddenField'; 
    document.getElementById(theField+"Label").setAttribute('className', 'hiddenField'); 
    document.getElementById(theField+"Text").className = 'hiddenField'; 
    document.getElementById(theField+"Text").setAttribute('className', 'hiddenField'); 
    document.getElementById(theField+"Break").className = 'hiddenField'; 
    document.getElementById(theField+"Break").setAttribute('className', 'hiddenField'); 
} 

我測試它只是簡單地用「狀態」作爲第二個變量來確保它的工作......並沒有。我一直得到「Uncaught TypeError:無法設置未定義的屬性'禁用'。我敢肯定它的語法錯誤。我對這個函數的調用是:

hideAddressField(theForm,state); 

形式的名稱是「theForm」,以及讓我想通變量「theForm」是被分配「theForm」的值,而變量「theField」正在分配「狀態」的值和兩個函數應該是等價的。很明顯不是。

我哪裏錯了?

+0

[Dynamic object property name](http://stackoverflow.com/questions/4244896/dynamic-object-property-name)和[javascript object,access variable property name?](http:// stackoverflow .com/questions/4255472/javascript-object-access-variable-property-name)以及其他人。 –

+0

另外MDN文檔可能會有所幫助:https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects –

+0

感謝您的支持。 – bcsteeve

回答

1

您必須使用theForm[theField]語法,因爲「theField」是一個包含屬性名稱的變量,而不是屬性本身。另外,您需要將state作爲字符串傳遞。

+0

我可以得到更多細節嗎?我嘗試了我認爲你的意思,現在我只是得到「Uncaught SyntaxError:意外的標識符」。沒關係!我的編輯器自動完成了一些操作並刪除了一個。我現在明白了,謝謝!人們在哪裏學習各種語法和符號?我首先嚐試了Google,甚至不知道要搜索什麼。 – bcsteeve

+0

@ user1438619:雖然MDN JavaScript指南值得一讀:https://developer.mozilla.org/en/JavaScript/Guide –

+0

這將是一次Mozilla的網站回來:)我一直試圖安裝Firefox整天,我可以得到螢火蟲。 – bcsteeve