0

这是我注意到的一个奇怪的行为。我没有重置文档,而是在添加后立即使用它,并且它包含的先前元素不存在。

我应该这样清除它吗?

frag_inner = '';

有我不知道的副作用吗?

frag_outer = NS.createDocumentFragment();
frag_inner = NS.createDocumentFragment();

NS.eachIndex(obj, function(val) {

    // fragment element - inner

    // image element

    val.view_picture = (val.picture === '0') ? this.A.images + 'generic_large.jpg' :
            this.A.pictures + val.h_file  + '-2.jpg';
    img_element = $A.createElement('img');
    img_element.className = 'tweet';
    img_element.src = val.view_picture;
    frag_inner.appendChild(img_element);

    // link element

    link_element = $A.createElement('a');
    link_element.className = 'tweet';
    link_element.innerHTML = val.name + ' posted ' +
            this.prettyTime(val.time) + '<br>';
    frag_inner.appendChild(link_element);

    // paragraph element

    par_element = $A.createElement('p');
    par_element.className = 'tweet';
    par_element.innerHTML = val.tweet;
    frag_inner.appendChild(par_element);

    // div element

    div_element = $A.createElement('div');
    div_element.className = 'tweet';
    div_element.appendChild(frag_inner);

    // append the div which is now populated

    frag_outer.appendChild(div_element);

}, this);
4

1 回答 1

2

I think it's actually the expected behaviour, as...

1) it's a well-known feature of Node.appendChild to move existing Nodes. As said in the docs (MDN)...

[Node.appendChild]... adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.

2) when you append documentFragment, you actually append all its children (MDN again):

Various other methods can take a document fragment as an argument (e.g., any Node interface methods such as Node.appendChild and Node.insertBefore), in which case the children of the fragment are appended or inserted, not the fragment itself.

The point is, when you do someNode.append(documentFragment), you remove all its children from it, then append them to someNode. That's why documentFragment is empty as result.


Note that when you do this...

frag_inner = '';

... you're not clearing the documentFragment stored in this variable - you store a new value (an empty string, obviously) in it instead. The very first attempt to work with it as with documentFragment should result in something like TypeError: Object has no method 'appendChild'.

于 2013-06-10T19:19:35.507 回答