javascript - 纯Javascript : convert a string to NodeList

标签 javascript html foreach domparser nodelist

使用纯 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 live NodeList 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/

相关文章:

javascript - Fusioncharts 使用 vue 和 laravel 显示来自 Controller 的数据,其中条件是 count 和 group

javascript - 在返回 false 的函数中使用 jQuery .preventDefault 和 .stopPropagation

javascript - 在 AngularJS 中发出 GET 请求后,在 2 个 Controller 之间共享全局变量失败

html - 增加图像的高度,保持宽度不变

javascript - FUNCTION中如何返回为多维数组的输出

javascript - SAPUI5模拟服务器不接收请求

javascript - 如何在 Div 中动态添加段落?

javascript - 叶节点 cytoscape 的不同行为

javascript - 当一个简单的 For Loop 工作正常时,我的 forEach 方法有什么问题

PHP循环curl请求一个一个