简体   繁体   English

append 按钮如何<li>使用 forEach 循环标记 javascript</li>

[英]how to append the button to each <li> tag in javascript using forEach loop

I want to append the button tag to each of the 6 li tags using a forEach loop but after running the below code I am only getting a button tag on the 6th (last) li tag.我想 append 使用forEach循环将button标签添加到 6 个li标签中的每一个,但是在运行以下代码后,我只在第 6 个(最后一个) li标签上获得了一个button标签。 Please help and let me what I am doing wrong.请帮助并让我做错了什么。

 var button = document.createElement('button'); button.appendChild(document.createTextNode('delete')); var spam = document.createElement('spam'); var li = document.querySelectorAll('li'); li.forEach(function(i) { i.appendChild(button); });
 <body> <h1>Shopping List</h1> <p id="first">Get it done today</p> <input id="userinput" type="text" placeholder="enter items"> <button id="enter" width='50px'>Enter</button> <ul> <li class="bold red" random="23">Notebook</li> <li>Jello</li> <li>Spinach</li> <li>Rice</li> <li>Birthday Cake</li> <li>Candles</li> </ul> </body>

Just move document.createElement('button') in forEach Loop of yours只需在你的forEach Loop中移动document.createElement('button')

 var spam = document.createElement('spam'); var li = document.querySelectorAll('li'); li.forEach(function(i) { var button = document.createElement('button'); button.appendChild(document.createTextNode('delete')); i.appendChild(button); });
 <body> <h1>Shopping List</h1> <p id="first">Get it done today</p> <input id="userinput" type="text" placeholder="enter items"> <button id="enter" width='50px'>Enter</button> <ul> <li class="bold red" random="23">Notebook</li> <li>Jello</li> <li>Spinach</li> <li>Rice</li> <li>Birthday Cake</li> <li>Candles</li> </ul> </body>

as @Shubh said you need to move the createElement inside the foreach loop.正如@Shubh 所说,您需要将 createElement 移动到 foreach 循环内。 and create a new button element each time and append it to the li elements.并每次创建一个新的按钮元素,并将 append 它添加到 li 元素。 because the variable button that you created at the beginnig is refering to the created element.因为您在开始时创建的变量按钮是指创建的元素。 each iteration you are just assigning it to another li node.每次迭代你只是将它分配给另一个 li 节点。 so:所以:

li.forEach(function(item){ 
      var button=document.createElement('button');
  button.appendChild(document.createTextNode('delete'));
  item.appendChild(button);
   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM