我正在尝试对我查询的 nodeList 的顺序进行排序并将它们替换到 DOM 上,但是使用下面的解决方案我在 HTML 中变得未定义。有人知道这是怎么回事吗?
const container = elem[0].childNodes[1];
let graphs = container.querySelectorAll('visualization-container[data-graph]');
const sorted = [].slice.call(graphs).sort((a, b) => {
const first = a.getAttribute('data-graph');
const second = b.getAttribute('data-graph');
return scope.visualizationsOrder[first] > scope.visualizationsOrder[second] ? 1 : -1;
});
console.log(sorted); // Sorted is correct
container.replaceWith(sorted); // error here
这是一个说明问题的 jsfiddle https://jsfiddle.net/ejdq1xyz/
这里的“问题”是,这sorted
是一个Nodes数组。
我不太确定为什么要用其排序的子项替换容器...
如果不应移除容器,则必须使用.appendChild()
,.append()
或.insertAdjacentElement()
代替.replaceWith()
.
并且因为sorted
是一个数组,您必须使用for
循环或.forEach()
以下方式一个一个地添加节点:
sorted.forEach(n => container.appendChild(n));
sorted.forEach(n => container.append(n));
sorted.forEach(n => container.insertAdjacentElement("beforeEnd", n));
如果.append()
您还可以使用.apply()
(ES5 版本)或 ES6扩展运算符/语法,...
因为它也将接受一组Nodes / DOMStrings:
container.append.apply(container, sorted);
container.append(...sorted);
const order = {
identifierOne: 4,
identifierTwo: 3,
identifierThree: 1,
identifierFour: 2
};
const container = document.querySelector('.container');
const graphs = container.querySelectorAll('.graph[data-graph]');
const sorted = [].slice.call(graphs).sort((a, b) => {
const first = a.getAttribute('data-graph');
const second = b.getAttribute('data-graph');
return order[first] > order[second] ? 1 : -1;
});
sorted.forEach(n => container.appendChild(n));
<div class='container'>
<div class='graph' data-graph='identifierOne'>4</div>
<div class='graph' data-graph='identifierTwo'>3</div>
<div class='graph' data-graph='identifierThree'>1</div>
<div class='graph' data-graph='identifierFour'>2</div>
</div>
如果容器应该被替换而不是你可以使用.replaceWith()
的.apply()
或者扩展运算符/语法...
container.replaceWith.apply(container, sorted);
container.replaceWith(...sorted);
const order = {
identifierOne: 4,
identifierTwo: 3,
identifierThree: 1,
identifierFour: 2
};
const container = document.querySelector('.container');
const graphs = container.querySelectorAll('.graph[data-graph]');
const sorted = [].slice.call(graphs).sort((a, b) => {
const first = a.getAttribute('data-graph');
const second = b.getAttribute('data-graph');
return order[first] > order[second] ? 1 : -1;
});
container.replaceWith.apply(container, sorted);
//container.replaceWith(...sorted);
<div class='container'>
<div class='graph' data-graph='identifierOne'>4</div>
<div class='graph' data-graph='identifierTwo'>3</div>
<div class='graph' data-graph='identifierThree'>1</div>
<div class='graph' data-graph='identifierFour'>2</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句