在同一循环中多个阑尾呼叫
listCities.forEach(function(city){
let option = document.createElement('option');
option.value = city;
listFrom.appendChild(option);
listTo.appendChild(option);
});
我有一个数组,我想将每个字符串作为选项添加到两个数据师(列表From和ListTo)中。问题在于,无论我输了什么顺序,只有列表中的最后一个将选项添加到它们中。
有没有办法在相同的foreach循环中执行此操作,或者我必须创建两个不同的循环来完成完全相同的事情。
我只是很难理解其背后的逻辑。
listCities.forEach(function(city){
let option = document.createElement('option');
option.value = city;
listFrom.appendChild(option);
listTo.appendChild(option);
});
I have an array and I want to add each string in it as options to two datalists (listFrom and listTo). The problem is that no matter the order I put them, only the last one of the list gets the options added to them.
Is there a way to do this in the same forEach loop or do I have to create two different loops that do exactly the same thing.
I'm just having trouble understanding the logic behind it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
附录时,您将元素移至最后提到的容器,因为该元素仅存在一次。
这比创建一个选项,克隆并添加两次要快得多:
When you appendChild, you MOVE the element to the last mentioned container since the element only exists once in the DOM.
This is a LOT faster than creating an option, cloning it and appending it twice:
一个元素只能在一个地方存在。您需要制作一个 clone> clone
An element can only exist in one place. You need to make a clone of it