Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么修复后的元素会失去彼此之间的偏移?_Javascript_Html_Clone - Fatal编程技术网

Javascript 为什么修复后的元素会失去彼此之间的偏移?

Javascript 为什么修复后的元素会失去彼此之间的偏移?,javascript,html,clone,Javascript,Html,Clone,我正在尝试为我的站点实现书签功能,并对此进行测试: <html> <head> <title>test bookmark</title> <script type='text/javascript' src='libs/bookmarks.js'></script> </head> <body> <input type =

我正在尝试为我的站点实现书签功能,并对此进行测试:

<html>
    <head>
        <title>test bookmark</title>
        <script type='text/javascript' src='libs/bookmarks.js'></script>
    </head>
    <body>
        <input type = "text" id = "txt_id" />
        <input type = "button" value = "create bk" onclick = "createBookmark();" />
        <input type = "button" value = "restore bk 0" onclick = "restoreBookmarkNumber(0);" />
    </body>
</html>

测试书签
bookmarks.js:

function Bookmark(of_elem, name)
{
    this.name = name;
    this.of_elem = of_elem;    
    this.elems = new Array();

    for (var i = 0; i < of_elem.children.length; i++)
        this.elems.push(of_elem.children[i].cloneNode(true));

    return this;
};

Bookmark.prototype.restore = function ()
{
    while (this.of_elem.hasChildNodes())
        this.of_elem.removeChild(this.of_elem.lastChild);

    for (var i = 0; i < this.elems.length; i++)
        this.of_elem.appendChild(this.elems[i].cloneNode(true));
};

var bookmarks = new Array();

function createBookmark()
{
    var name = prompt("Enter bookmark name", "Bookmark " + bookmarks.length);
    var bk = new Bookmark(document.body, name);
    bookmarks.push(bk);
}

function restoreBookmarkNumber(num)
{
    var bk = bookmarks[num];

    if (bk)
        bk.restore();
}
函数书签(元素、名称)
{
this.name=名称;
这个元素的数量=元素的数量;
this.elems=新数组();
for(var i=0;i

出于某种奇怪的原因,恢复书签后,文本框和按钮之间的空间消失了,但我不明白为什么会发生这种情况。我很清楚地克隆了所有元素,那么它还需要什么呢?

在使用
childrends
而不是
childNodes
(例如
书签
构造函数)的地方,您只需要处理元素子元素(因为这是
子元素
childNodes
)。自始至终使用
childNodes
,以确保在元素之间维护文本节点,因为元素之间的文本节点可能非常重要(例如,对于间距)

您的原稿将丢失间距:

函数书签(元素、名称)
{
this.name=名称;
这个元素的数量=元素的数量;
this.elems=新数组();
for(var i=0;i

测试书签