简体   繁体   English

为什么不能按正向顺序删除样式?

[英]Why can't styles be removed in forward order?

I modified the question/answer in the SO post below to remove styles, in forward order. 我在下面的SO帖子中修改了问题/答案,以正向顺序删除样式。

The question/answer removes scripts in reverse order. 问题/答案以相反的顺序删除脚本。

It did not work. 这没用。 However, if I changed it back to reverse order things worked. 但是,如果我将其更改为逆序,则可以正常工作。

My guess, was that if you remove style[0] , that style[1] would immediately update to become style[0], in an example w/ only two styles. 我的猜测是,如果你删除style[0] ,那个style[1]会立即更新为样式[0],在一个例子中只有两个样式。 Hence the loop would fail. 因此循环会失败。

Is this correct? 这个对吗?

Is the style array updated near instantaneously as it is modified? 样式数组是否在修改后立即更新?

Reference Post 参考文章

var scripts  = document.getElementsByTagName("script");
for (var i=scripts.length; i--; ){
   (scripts[i]).parentNode.removeChild(scripts[i]);
}

Your guess is correct; 你的猜测是正确的; getElementsByTagName returns a live "array" (which is not actually an array, but rather a NodeList or HTMLCollection , depending on browser and version) that reflects subsequent updates to the DOM. getElementsByTagName返回一个实时 “数组”(实际上不是一个数组,而是一个NodeListHTMLCollection ,具体取决于浏览器和版本),它反映了对DOM的后续更新。

So, you can write: 所以,你可以写:

var styles = document.getElementsByTagName("style");
while (styles.length) {
    styles[0].parentNode.removeChild(styles[0]);
}

That said, there's no reason to prefer this way. 也就是说,没有理由这样做。 Since JavaScript is run in the same thread that paints the UI, the result of removing the styles won't take effect until after the loop is complete, so the order doesn't matter to you. 由于JavaScript在绘制UI的同一个线程中运行,因此删除样式的结果直到循环完成后才会生效,因此顺序对您无关紧要。

Useful MDN links: 有用的MDN链接:

From https://developer.mozilla.org/en-US/docs/Web/API/element.getElementsByTagName : 来自https://developer.mozilla.org/en-US/docs/Web/API/element.getElementsByTagName

elements is a live NodeList (but see the note below) of found elements in the order they appear in the subtree. elements是按照它们出现在子树中的顺序,找到元素的实时NodeList(但请参阅下面的注释)。 If no elements were found, the NodeList is empty. 如果未找到任何元素,则NodeList为空。

So as soon as you remove elements[0], elements[0] is filled with elements[1], thus removing elements[1] (unless there was an elements[2]). 因此,只要删除元素[0],元素[0]就会填充元素[1],从而删除元素[1](除非有元素[2])。

You can do it in "normal" order like this (although it's not as performant due to the repeating test of scripts.length): 您可以像这样以“正常”顺序执行此操作(尽管由于重复测试scripts.length而不是高效):

var scripts  = document.getElementsByTagName("script");
while (scripts.length) {
    (scripts[0]).parentNode.removeChild(scripts[0]);
}

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

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