为什么我们不能直接在循环中使用 "innerHTML" 函数而不是连接文本以获得垂直的书面列表?

why we cannot use "innerHTML" function directly in loop instead of concatenating the text in order to get a vertical written list?

为什么我们不能直接在循环中使用“innerHTML”函数而不是连接文本以获得垂直书写列表?

const pk = document.getElementById('pk');

function validation(){
    var word = document.getElementById('name').value;
    var arr = word.split(" ");
    var i;
    for (i = 0; i < arr.length; i++){
        console.log(i);
        let boko = document.createElement('div');
        boko.setAttribute('id', 'boko');
        pk.appendChild(boko);
        document.getElementById("boko").innerHTML = i;
    }
}

这里我没有得到输出 0 1 2 3 而是我只得到 3... 我替换了 " text += "The number is " + i + "<br>";" 这条语句..但它似乎不起作用请帮我解决问题。

您已经有了对您的 div 的引用,因此您不需要为它分配一个 id -- 您可以直接设置它的 innerHTML

const pk = document.getElementById('pk');

function validation() {
    var word = document.getElementById('name').value;
    var arr = word.split(" ");
    for (var i = 0; i < arr.length; i++){
        let boko = document.createElement('div');
        boko.innerHTML = i;
        pk.appendChild(boko);
    }
}

检查 documentation for createElement(...) -- 它 returns 一个 HTMLElement 你可以直接修改(至少在 createElement('div') 的情况下) )