【问题标题】:Cannot display <LI> items无法显示 <LI> 项
【发布时间】:2020-12-31 02:54:02
【问题描述】:

我不知道为什么我不能将 LI 项目添加到#historial &lt;UL&gt;

如果 for 循环在函数内部,则列表会显示一些重复的元素。我几乎可以肯定 for 循环应该是现在的样子,在函数之外。

有人可以帮帮我吗?

let terminos= [];

    
    function agregar(){

        let termino = document.querySelector('#busqueda').value;
        console.log(termino);

        if( terminos.length >= 5){
            terminos.shift();
            terminos.push(termino);
        }else{
            terminos.push(termino);
        }

            console.log(terminos); 
            document.querySelector('#busqueda').value ='';
           
            
    
    }

        
    let boton= document.querySelector('#enviar');
    boton.addEventListener('click', agregar);

    for( let i =0 ; i< terminos.length; i++){
        
        document.querySelector('#historial').innerHTML += `<li> ${terminos[i]}</li>`;
    }
#historial{ 
background-color: tomato;
  width:50vw;
  height:300px;
  color:white;
  font-size:20px;
}
<label for="busqueda"> Término</label>
    <input type="text" id="busqueda"> <br>
    <button type="submit" id="enviar"> Enviar</button>
<p> UL#historial</p>
    <ul id="historial">

    </ul>

【问题讨论】:

    标签: javascript html dom


    【解决方案1】:

    试试这个 https://stackoverflow.com/a/20673977/10801086

    您应该appendChild 而不是设置innerHtmlul 元素

    ...
     let boton= document.querySelector('#enviar');
        boton.addEventListener('click', function1);
    
    function function1() {
      var ul = document.querySelector('#historial');
      var li = document.createElement("li");
      li.appendChild(document.createTextNode(document.querySelector('#busqueda').value));
      ul.appendChild(li);
    }
    

    【讨论】:

    • 在这里解释原因更具教学性,而不是链接到外部指南。
    【解决方案2】:

    好的,这是一个非常基本的场景,简单来说,可以通过将li 元素附加到ul 元素来解决。请看一下sn-p。

    希望这对您有所帮助。干杯!!

    function addElementToList() {
    
      var listElement = document.getElementById("historial");
      for (var i = 0; i < 5; i++) { //this will be your `terminos.length` loop
        var li = document.createElement("li");
    
        li.appendChild(document.createTextNode("New Element"));
        listElement.appendChild(li);
      }
    
    }
    <html>
    
    <body>
      <div>
        Dynamic list generation:
    
        <ul id="historial">
    
        </ul>
    
        <button onClick="addElementToList()" /> Add New Element
      </div>
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 2011-03-25
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多