javascript - 为什么 Microsoft Edge 在呈现页面之前重新排序 html 属性?

标签 javascript html microsoft-edge

所以我写了一些 Javascript,当用户点击按钮时滚动到文档中的某个位置:

document.getElementById("navContact").addEventListener("click", scrollToSection);

function scrollToSection() {
    /* this = element on which the user clicked */
    smoothScroll(this.attributes[0].value.split("#")[1]);
}

它很好、简单、易于阅读和调试。唯一的问题是它通过从命名节点映射中读取它来获取它必须滚动到的部分的名称。在我的标记中,属性的顺序如下:

<a href="#contact_us" id="navContact"></a> 
<--! document.getElementById("navContact").attributes = [href="contact_us", id="navContact"] -->

但是当我在 Edge 的 DOM 资源管理器中检查它时,属性被重新排序:

<a id="navContact" href="#contact_us"></a>
<--! document.getElementById("navContact").attributes = [id="navContact", href="contact_us"] -->

根据 Josiah Keller 的建议,我将 js 更改为使用 element.getAttribute() 而不是 this.attributes

与此同时,我很想知道 Edge 为什么要这样做?

最佳答案

.attributes 返回一个 NamedNodeMap。 According to MDN :

The NamedNodeMap interface represents a collection of Attr objects. Objects inside a NamedNodeMap are not in any particular order, unlike NodeList, although they may be accessed by an index as in an array.

虽然您可以使用 this.attributes[0] 引用它,但您会注意到您不能 push 它,因为它不是数组。它是一个对象,它是在没有考虑顺序的情况下构建的,因此它可能不是 Edge 中的错误。它仍在返回它应该返回的内容,即无序对象。

正如其他人所建议的那样,您应该专门获取 href,但希望这能说明为什么它没有像您想象的那样工作。

关于javascript - 为什么 Microsoft Edge 在呈现页面之前重新排序 html 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45002558/

相关文章:

javascript - 动态更改 CSS 样式

javascript - OpenLayers:为什么浏览器中的console.log可以找到该变量

javascript - 将内容插入 html - maxmind geoip2

html - 文本区域和文本缩进 : placeholder doesn't work properly on EDGE

javascript - 按下按钮后停止和启动动画(Javascript)

javascript - 我如何知道在 jQuery 中选择了哪个 radio 输入?

jquery - 访问动态生成的id

javascript - 在 javascript 中解析 xml 服务的最佳方法?

html - :hover and disappearing scrollbar in Edge

即使使用 -ms 前缀,CSS Grid 也无法在 IE11 和 Edge 上运行