2014-10-07 32 views
0
的一切都在這裏

首先是該項目的小提琴作爲一個整體: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"; 
} 
+0

代碼太多。請張貼削減版本。 – 2014-10-07 13:34:44

+1

只是FYI,您不必使用'.setAttribute()'來設置DOM元素屬性。只需將它們設置爲普通的對象屬性。 – Pointy 2014-10-07 13:35:08

+0

@torazaburo你走了。 – Chrillewoodz 2014-10-07 13:37:38

回答

0

的一個問題是這樣的,你的JavaScript代碼是「負載」處理器,你設置你已經配置的jsfiddle以一種無法使用的方式處理事件處理程序。該代碼應該是這樣的:

var select = document.createElement("select"); 
select.onchange = otherParty; 
select.style.marginLeft = indent; 
container.appendChild(form); 
td.appendChild(select); 

現在,一旦你這樣做,你會發現這行不通:

inputs.style.visibility = "visible"; 

你根本無法做到這一點。你必須遍歷從getElementsByTagName()返回的節點列表,並分別設置每個節點的樣式。

+0

這工作,我不明白你爲什麼不能一次性設置所有的CSS屬性,而不是必須迭代?這是爲什麼? – Chrillewoodz 2014-10-07 13:46:55

+0

@Chrillewoodz因爲DOM API根本不允許這樣做。從'.getElementsByTagName()'返回的對象是一個名爲NodeList的東西。它提供了訪問節點的設施,但不能做其他任何事情。這種事情就像jQuery提供的DOM庫一樣方便。 – Pointy 2014-10-07 13:49:09

+0

所以技術上我可以用Jquery來代替它?同時也可以這樣做,當下拉菜單中的任何內容(如現在)被選中時,輸入不會出現,但只有最後一件事情? – Chrillewoodz 2014-10-07 14:00:52