首先是該項目的小提琴作爲一個整體:http://jsfiddle.net/7tj9xjb8/如何訪問由函數創建的HTML元素?元素是「不確定」,因此未CSS應用,能夠
現在,我創建一個包含有一些選擇的選項和輸入字段的表形式。我想要做的事情是在選擇最後一個選擇選項(「Väljannat parti」)後,將此窗體中輸入的可見性css屬性從隱藏更改爲可見。這應該用一個名爲otherParty()的函數完成,該函數在select標籤中使用onchange屬性進行調用。然而,變量「inputs」是未定義的,因爲內容在被調用時似乎不在實際的HTML中,這很奇怪,因爲該函數在腳本完成之前不會被調用。這可能是因爲它是由另一個函數創建的,但是我的問題是,我該如何解決這個問題才能起作用?
這裏是代碼的切出的版本:
function createDropDown() {
//These are the selects that call the otherParty function onchange.
var select = document.createElement("select");
select.setAttribute("onchange", "otherParty()");
select.style.marginLeft = indent;
container.appendChild(form);
td.appendChild(select);
for (i = 0; i < type.length; i++) {
var option = document.createElement("option");
option.value = option.innerHTML = type[i];
select.appendChild(option);
}
table.appendChild(tr);
tr.appendChild(td);
//These are the inputs that should show up
if (inputTrue) {
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("name", inputType);
input.setAttribute("alt", inputType);
input.setAttribute("id", inputType);
input.setAttribute("placeholder", "Annat parti");
input.style.visibility = "hidden";
td.appendChild(input);
}
table.appendChild(tr);
tr.appendChild(td);
} //End of function
//Makes the inputs show up
function otherParty() {
var inputs = document.getElementsByTagName('input'); //grab all the inputs in the form once they've been created
inputs.style.visibility = "visible";
}
代碼太多。請張貼削減版本。 – 2014-10-07 13:34:44
只是FYI,您不必使用'.setAttribute()'來設置DOM元素屬性。只需將它們設置爲普通的對象屬性。 – Pointy 2014-10-07 13:35:08
@torazaburo你走了。 – Chrillewoodz 2014-10-07 13:37:38