使用纯 JavaScript,我尝试将字符串转换为 NodeList 并将每个 NodeListItem 附加到容器元素,使用 inf forEach。
字符串列表有 6 个项目,但只附加了 3 个。为什么?
var controlsString = '<button class="{{namespace}}_prev" onclick="isotype_sliders[{{index}}].slide_to(\'prev\');">Slide to prev</button>'+
'<button class="{{namespace}}_pause" onclick="isotype_sliders[{{index}}].pause(); this.style.display=\'none\'; this.nextElementSibling.style.display=\'initial\';">Pause</button>'+
'<button class="{{namespace}}_play" style="display: none;" onclick="isotype_sliders[{{index}}].play(); this.style.display=\'none\'; this.previousElementSibling.style.display = \'initial\';">Play</button>'+
'<button class="{{namespace}}_next" onclick="isotype_sliders[{{index}}].slide_to(\'next\');">Slide to next</button>'+
'<button class="{{namespace}}_shuffle" onclick="isotype_sliders[{{index}}].shuffle();">Shuffle</button>'+
'<button class="{{namespace}}_slide_to" onclick="isotype_sliders[{{index}}].slide_to(2);">Slide to 2</button>';
var container = document.getElementById('container');
var getNodes = str => new DOMParser().parseFromString(str, 'text/html').body.childNodes;
var controlsNodes = getNodes(controlsString);
console.log(controlsNodes);
controlsNodes.forEach(function(controlNode, controls_index, listObj){
console.log(controlNode);
container.appendChild(controlNode);
});
看看我在 JSFiddle 上的实验: https://jsfiddle.net/lorenzodetomasi/kjhac52y/
谢谢。
最佳答案
关键问题是直接在 childNodes
的结果上使用 forEach
。引用 docs :
Node.childNodes
read-only property returns a liveNodeList
of child nodes of the given element [...]
换句话说,每次从 controlsNodes
添加一个节点时,都会将其从 DOM 中的一个位置移动到另一个位置,并重建相应的 NodeList - 但 forEach()
code> 只是不关心并前进到该 NodeList 的下一个索引。这就是跳过原始集合的每个偶数元素的原因。
有几种解决方法。最直接的是将动态 NodeList 转换为静态数组 - 使用 Array.from()或spread operator :
[...controlsNodes].forEach(function(controlNode, controls_index, listObj){
console.log(controlNode);
container.appendChild(controlNode);
});
另一种方法是咬紧牙关 - 考虑到 NodeList 的动态特性:
while (controlsNodes.length !== 0) {
container.appendChild(controlsNodes[0]);
}
关于javascript - 纯Javascript : convert a string to NodeList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49773329/