[英]Using Javascript function variables to define a DOM element
我正在使用yes / no dropdownbox通過CSS隱藏條件表單元素。 如果我手動定義表單名稱和元素名稱,它會很好地工作,但是如果我嘗試通過變量定義它們,它將無法正常工作。 我已經進行了大約一個小時的故障排除和研究,但無濟於事。 這是我的Javascript函數。
function binaryHideShow(formName, elementName)
{
if (document.forms["'" + formName + "'"].elementName.value == "yes")
{
document.getElementById("'" + elementName + "'").setAttribute("class","show");
}
else
{
document.getElementById("'" + elementName + "'").setAttribute("class","hide");
}
}
這是HTML元素。
<select name="PrimaryFiledBankruptcyDropDownList" onchange="binaryHideShow(this.form.name, this.attributes['name'].value);">
<option value=""></option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<div id="PrimaryFiledBankruptcyDropDownList">
<label for="PrimaryBankruptcyTypeDropDownList">Bankruptcy Type:</label>
<select name="PrimaryBankruptcyTypeDropDownList" onchange="">
<option value=""></option>
<option value="chapter-7">Chapter 7</option>
<option value="chapter-13">Chapter 13</option>
</select>
</div>
我已經確保我在html端的this語句提取正確的元素。
為了清楚起見,如果我按照下面的示例手動輸入變量名稱,它將正常工作,並且html this語句返回下面我使用的確切名稱。
function binaryHideShow()
{
if (document.forms["ProgramApplicationForm"].PrimaryFiledBankruptcyDropDownList.value == "yes")
{
document.getElementById("PrimaryFiledBankruptcyDropDownList").setAttribute("class","show");
}
else
{
document.getElementById("PrimaryFiledBankruptcyDropDownList").setAttribute("class","hide");
}
}
您的函數無法訪問表單中的元素,請嘗試執行以下操作:
function binaryHideShow(formName, elementName)
{
if (document.forms[formName][elementName].value == "yes")
{
document.getElementById(elementName).setAttribute("class","show");
}
else
{
document.getElementById(elementName).setAttribute("class","hide");
}
}
從
document.forms["'" + formName + "'"]
至
document.forms[ formName ]
否則,您將像使用“'PrimaryBankruptcyTypeDropDownList'”一樣傳遞名稱(請注意雙引號)。
這應該可以幫助您入門。
的HTML
<form name="MyForm" id="MyForm">
<select name="PrimaryFiledBankruptcyDropDownList"nchange="binaryHideShow(this,this.form);">
<option value=""></option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</form>
的JavaScript
function binaryHideShow(element,form) {
console.log("Element Name: " + element.name);
console.log("Form Name: " + form.name);
if(element.value == "yes") {
console.log('sure does');
} else {
console.log('nope');
}
}
離題-但是,您可能會發現這很有用...
研究將動作從視圖中分離出來-含義:擺脫“ onchange”事件,如果可能的話-考慮使用jQuery。
一些適合您的讀物:
我最終弄清楚了。 為了使用document.forms的元素部分,您必須使用內部變量來指定elements []:
function binaryHideShow(formName, elementName)
{
if (document.forms[formName].elements[elementName].value == "yes")
{
document.getElementById(elementName).setAttribute("class","show");
}
else
{
document.getElementById(elementName).setAttribute("class","hide");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.