尝试从输入到span元素的输入字段中获取值。每个输入字段都有一个ID,它们在数组“ tekstvelden”中。每个span都有一个类,它们在数组“ spans”中
function getValue(elementId) {
return document.getElementById(elementId).value;
};
function schrijfVerhaal() {
var tekstvelden = ['znw', 'bvn', 'bvn2', 'held', 'prinses'];
var spans = ['znwT', 'bvnT', 'bvn2T', 'heldT', 'prinsesT'];
tekstvelden.forEach(function(item, index) {
var inhoudVeld = getValue(item);
var spanClass = spans[index];
document.getElementsByClassName(spanClass).innerHTML = inhoudVeld;
});
};
答案 0 :(得分:1)
getElementsByClassName
返回找到的元素的HTMLCollection
。如果要更新集合的每个元素,请遍历这些元素并更新innerHTML
function getValue(elementId) {
return document.getElementById(elementId).value;
};
var tekstvelden = ['znw', 'bvn', 'bvn2'];
var spans = ['znwT', 'bvnT', 'bvn2T'];
tekstvelden.forEach(function(item, index) {
var inhoudVeld = getValue(item);
var spanClass = spans[index];
var elements = document.getElementsByClassName(spanClass)
for(let e of elements)
e.innerHTML = inhoudVeld;
});
<input id="znw" value="10" />
<input id="bvn" value="20" />
<input id="bvn2" value="30" />
<br>
<span class="znwT"></span>
<span class="bvnT"></span>
<span class="bvn2T"></span>
<br>
<span class="znwT"></span>
<span class="bvnT"></span>
<span class="bvn2T"></span>
答案 1 :(得分:1)
尝试document.getElementsByClassName(spanClass)[0].innerHTML
如果您想对所有人都这样做:
for (let i of document.getElementsByClassName(spanClass)){
i.innerHTML = ...;
}