有人可以帮我理解appendChild方法实际发生了什么吗?

问题描述 投票:0回答:2
<blockquote id="quote">
    No book can ever be finished. While working on it we learn
    just enough to find it immature the moment we turn away
    from it.
</blockquote>

<script>
    function elt(type) {
        var node = document.createElement(type);
        for (var i = 1; i < arguments.length; i++) {
            var child = arguments[i];
            if (typeof child == "string")
                child = document.createTextNode(child);
            node.appendChild(child);
        }
        return node;
    }

    document.getElementById("quote").appendChild(
        elt("footer", "—",
            elt("strong", "Karl Popper"),
            ", preface to the second editon of ",
            elt("em", "The Open Society and Its Enemies"),
            ", 1950"
        )
    );
</script>

有人可以帮我理解appendChild方法中实际发生的事情

的document.getElementById( “报价”)的appendChild(ELT(...))。

javascript dom
2个回答
1
投票

看起来elt函数采用type的参数,这是要创建的元素的类型(请参阅elt("footer"))。它还处理一些未指定数量的参数;对于每个作为字符串的参数,它会创建一个包含该字符串的textNode

appendChild方法简单地调用elt方法,在你的例子中,一个参数,一个函数调用(elt()),并且该函数调用包含六个参数,其中两个是elt()函数调用 - 每个参数包含两个参数,两者都是字符串。

那是你在找什么?


0
投票

elt调用包含6个参数,其中两个参数是elt()函数调用。由于“强”和“em”将是页脚的子元素,因此elt函数执行的顺序如下。

第一个elt函数通过调用elt("strong", "Karl Popper")来构建子元素

elt("em", "The Open Society and Its Enemies")

最后,elt("footer", "-", remaining arguments..)函数被调用6个agrugments。当创建两个子节点时,它将附加文本“ - ”和“,第二个编辑的前言”和“1950”,并构建整个文本。

如果我错过任何内容,请随意发表评论。

© www.soinside.com 2019 - 2024. All rights reserved.