2017-07-25 60 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>