如何使用Javascript将数组中的元素插入HTML文档?

nszi6y05  于 2022-12-25  发布在  Java
关注(0)|答案(3)|浏览(201)

我正在尝试添加一个名为"taskList"的列表的元素,该列表由从input元素获得的值组成。
有人能帮帮我吗,我不明白为什么列表中的元素没有显示。

var taskList = [];

var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');

button.onclick = function(){
    var nHTML = '';
    var userEnteredText = input.value;
        taskList.push(userEnteredText);
    taskList.forEach(function(task){
        nHTML += '<li>'+task+'</li>';
    });
    document.getElementsByClassName('taskLists').innerHTML = '<ul>' + nHTML + '</ul>';
}
<div class="wrapper">
    <header>To-Do List</header>
    <div class="taskAdder">
            <input id="takeInput" type="text" placeholder="Add your new To-Do">
            <button id="addInput" class="button" type="button" >➕</button>
    </div>
        <div class="taskLists">

        </div>
    <div class="footer">
        <span> You have <span class="pendingTasks"></span> tasks left </span> 
        <button type="button" class="button">Clear All</button>
    </div>
</div>

我试着检查了几次,但HTML文档中没有任何内容更新

zujrkrfu

zujrkrfu1#

不应该追加到innerHTML,而是使用createElement生成li,然后将新元素的innerHTML设置为input.value,并使用appendChild将其追加到列表中

var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
var tlist = document.getElementsByClassName('taskLists')[0];

button.onclick = function(){
    let e = document.createElement('li');
    e.innerHTML = input.value
    tlist.appendChild(e)
    
    // Optionally, clear the input field to prevent double adding the same task
    input.value = '';
}
<div class="wrapper">
    <header>To-Do List</header>
    <div class="taskAdder">
            <input id="takeInput" type="text" placeholder="Add your new To-Do">
            <button id="addInput" class="button" type="button" >➕</button>
    </div>
        <div class="taskLists">

        </div>
    <div class="footer">
        <span> You have <span class="pendingTasks"></span> tasks left </span> 
        <button type="button" class="button">Clear All</button>
    </div>
</div>
ny6fqffe

ny6fqffe2#

主要的错误是使用.getElementsByClassName时好像它只是一个元素而不是一个列表(不要忽略元素中的***s***!)
无论如何,我稍微重构了你的代码,使其每个目标都有更好的策略,并实现了清除任务列表的逻辑。

var taskList = [];

var input = document.getElementById('takeInput');
var buttonAdd = document.getElementById('addInput');
var buttonClear = document.getElementById('clearInput');
var tasksList = document.getElementById('tasksList');

buttonAdd.addEventListener('click', (event)=>{  
  addTask(input.value);  
});

buttonClear.addEventListener('click', (event)=>{  
  tasksList = [];
  document.querySelector('#tasksList ul').remove();
});

function addTask(value){
  if(taskList.length == 0){
    document.getElementById('tasksList').append( document.createElement('ul') );
  }
  taskList.push(value);
  const newLI = document.createElement('li');
  newLI.innerText = value;
  document.querySelector('#tasksList ul').append(newLI);
}
<body>
  <div class="wrapper">
  
    <header>To-Do List</header>
    
    <div class="taskAdder">
      <input id="takeInput" type="text" placeholder="Add your new To-Do">
      <button id="addInput" class="button" type="button">➕</button>
    </div>
    
    <div id="tasksList">
    </div>
    
    <div class="footer">
      <span> You have <span class="pendingTasks"></span> tasks left </span>
      <button id="clearInput" type="button" class="button">Clear All</button>
    </div>
    
  </div>
</body>
eqqqjvef

eqqqjvef3#

您只需要在任务列表中使用一个ID。
getElementsByClassName需要一个索引,这使得您的问题与What do querySelectorAll and getElementsBy* methods return?相同:
第一个月
也就是说,这里是一个完整的版本,使用了推荐的eventListener和相关的ID。

let tasks = [];
const taskList = document.getElementById('taskLists') 
const input = document.getElementById('takeInput');
const add = document.getElementById('addInput');
const pendingTasks = document.getElementById('pendingTasks');
const clear = document.getElementById('clear');

const showTasks = () => {
  taskList.innerHTML = `<ul>${tasks.map(task => `<li>${task}</li>`).join('')}</ul>`;
  pendingTasks.textContent = `${tasks.length} task${tasks.length != 1 ? "s" : ""}`;
};  
add.addEventListener('click', ()  => {
  var userEnteredText = input.value; 
  tasks.push(userEnteredText);
  showTasks();
});

clear.addEventListener('click', ()  => {
  tasks = [];
  showTasks();
});

taskList.addEventListener('click', (e) => {
  const tgt = e.target.closest('li');
  if (!tgt) return; // not a task
  const task = tgt.textContent;
  tgt.remove()
  tasks = tasks.filter(currentTask => currentTask != task); // remove from list
  showTasks()
});
showTasks(); //init
<div class="wrapper">
  <header>To-Do List</header>
  <div class="taskAdder">
    <input id="takeInput" type="text" placeholder="Add your new To-Do">
    <button id="addInput" class="button" type="button">➕</button>
  </div>
  <div id="taskLists"></div>
  <div class="footer">
    <span> You have <span id="pendingTasks"></span> left </span>
    <button type="button" id="clear">Clear All</button>
  </div>
</div>

相关问题