需要帮助修复不通过Dom显示的无序列表

问题描述 投票:0回答:1

逻辑似乎很合理,但是我的ul没有显示我要的内容。我已经使用了console.logs,并且可以肯定在函数poem中获得了displayPoem(poem),但是当我单击按钮时它没有出现。任何帮助将不胜感激!

const inputsList = document.querySelector('ol');
const poemsList = document.getElementById('savedThoughts');
const form = document.getElementById('')
const submitButton = document.getElementById('submitThoughts');
const startButton = document.querySelector('#startButton')


startButton.onclick = () => {
    const ranNum = generateRanNum();
    generateInputs(ranNum)
    changeToRestartText()
}

submitButton.onclick = () => {
    const poem = savePoem();
    console.log(poem)
    displayPoem(poem);
    clearForm()
}

const generateRanNum = () => {
    let randomNumber = Math.floor(Math.random() * 20);
    return randomNumber
}

const changeToRestartText = () => {
    startButton.textContent = 'Restart Game'
}


const generateInputs = (ranNum) => {
    const listItem = document.createElement('li');
    for(let i = 1; i <= ranNum; i++){
        const input = document.createElement('input');
        listItem.appendChild(input).setAttribute('type', 'text');
        console.log(ranNum)
    }
    inputsList.appendChild(listItem);
}

const savePoem = () => {
        let poemArr = [];
        const input = document.querySelectorAll('input');
        input.forEach(element => {
            poemArr.push(element.value);
        })
        // console.log(poemArr)
        return poemArr; 
}

const displayPoem = (poem) => {                    
    const savedPoem = document.createElement('li')
    const savedText = document.createElement('span')
    const deletePoem = document.createElement('button')

    console.log(poem)
    savedPoem.appendChild(savedText);
    savedText.textContent = poem.toString();
    savedPoem.appendChild(deletePoem);
    deletePoem.textContent = 'Delete';
    poemsList.appendChild(savedPoem)

    deletePoem.onclick = e => {
        poemsList.removeChild(savedPoem);
    }
}

const clearForm = () => {
    const inputLi = document.querySelectorAll('li');
    inputLi.forEach(element => {
        element.remove()
    })
}

小html片段

    <div >
       <ul id="savedThoughts">

       </ul>
    </div>
javascript html dom
1个回答
0
投票

您保存的列表项未显示,因为您的提交onclick调用displayPoem创建列表项,然后调用clearForm删除页面上的所有列表项。尝试inputLi = document.querySelectorAll('ol > li')

© www.soinside.com 2019 - 2024. All rights reserved.