2017-07-25 33 views
-1
function changeFunc9() { 
    var selectBox9 = document.getElementById("Schallamach"); 
    selectedValue9 =selectBox9.options[selectBox9.selectedIndex].value; 
    console.log(selectedValue9); 
} 
var values = [selectedValue1, selectedValue2, selectedValue3, 
selectedValue4, selectedValue5, selectedValue6, selectedValue7, 
selectedValue8, selectedValue9]; 

我沒有包含我的代碼的全部內容,因爲它對每個selectedValue#變量都是一致的。 selectedValues來自html中的選擇標籤,用戶從不同選項列表中選擇。我的功能只是將他們的選擇存儲在一個變量中,並將其記錄到控制檯,以便我可以確保它正常工作。我現在要做的就是使用這些變量,並在表中的td標籤中顯示變量的值。我對這項任務有困難。 selectedValues在數組中,以便它們是全局的。如果任何人都可以給我一些關於如何將這些變量分配給td的指導,那將是非常棒的,非常感謝。 我不想使用jQuery。 另外,我正在使用一個單獨的js文件並將其鏈接到html。我不知道這是否有所作爲。使用javascript變量值​​標籤

回答

0

從我的理解,你需要連續顯示「values」數組內的數據。如果是這種情況,請參考下面的代碼。

HTML - 定義表

<table border="1"><tr id="dataRow"></tr></table> 

JS

<script> 
var values = [selectedValue1, selectedValue2, selectedValue3, 
selectedValue4, selectedValue5, selectedValue6, selectedValue7, 
selectedValue8, selectedValue9]; 
for(var i=0;i<values.length;i++){ 
    document.getElementById("dataRow").innerHTML+="<td>"+values[i]+"</td>" 
} 
</script> 
+0

謝謝你,我會嘗試這個 –

+0

@FaithZellman,這樣做可以幫助您? – Ritz

+0

不,但這是我的第一個項目,我仍然在學習,所以其他地方可能有錯誤。 –

1

function valuesToTd(values) { 
 
    return values.map((value) => { 
 
    const td = document.createElement("td") 
 
    td.textContent = value 
 
    return td 
 
    }) 
 
} 
 

 
function addToTable(values, table) { 
 
    const tds = valuesToTd(values) 
 
    const tr = document.createElement("tr") 
 
    tds.forEach(tr.appendChild.bind(tr)) 
 
    table.appendChild(tr) 
 
} 
 

 
const selectedValues = ["one", "two", "three"] 
 
const table = document.querySelector("table") 
 
addToTable(selectedValues, table)
<table></table>