JavaScript insertBefore()的作用类似于appendChild()

时间:2012-10-31 15:40:08

标签: javascript

点击一个按钮,我想在当前选中的元素之前插入一个元素。我通过将最后点击的元素ID存储在变量中来处理“已选择”。

我的代码:

initialise.js

(function()
{
    main.page = parent.document;
}
)();

/** 
 *
 *      Easier than console.log();
 *
 */
function echo(string)
{
    console.log(string);
}

item_document_elements.js

// Example of the 2 parameters:
// controls.inserting_this = "canvas"
// select_element.selected = "default_div"    

main.page.getElementById("new_element_go").addEventListener
(
    "click", 
    function()
    {
        controls.insert_before(controls.inserting_this, select_element.selected);
    }, 
    false
);

controls.insert_before = function(element, selected)
{   
    echo("DEFINITELY INSERTING BEFORE");

    var id   = main.page.getElementById("new_element_id_input");
    var name = main.page.getElementById("new_element_name_input");

    // Return false if the input field is empty.
    if(id.value == "" || id.value == null || id.value == "undefined")
    {
        id.style.color = "#F00";
        id.value = "ID required";
        id.focus();

          return false;
    }

    // Check if the element ID is in the array.
    // If indexOf returns -1, it doesn't exist.
    if(create.element_array["name"].indexOf(id.value) != -1)
    {
        id.style.color = "#F00";
          id.value = "ID already exists";
          id.focus();

          return false;
    }
    else
    {
        var master_parent  = main.page.getElementById(selected).parentNode;
        var create_element = main.page.createElement(element);

          create_element.id         = id.value;
          create_element.style.border = "1px solid black";
          create_element.style.width  = "auto";
          create_element.style.height = "auto";
          create_element.textContent  = "New " + element;

          // Add element to array of elements in the document.
          create.element_array["name"].push(id.value);
          create.element_array["name"]["properties"].push(new element_properties);

          master_parent.insertBefore(create_element, selected); 
    }

        // End blackout window and remove popup.
        controls.end_darkness();
    }

该文件仅包含以下内容:

<div id="container" class="hovering selected" style="margin-right: auto; margin-left: auto; height: auto;">
    <div id="default_div" style="width: auto; height: 120px; border: 1px solid #999;"></div>
</div>

上面的代码总是在最后一个之后插入新元素,而不是之前。据我所知,该功能正在正确使用。如果没有,请告知。

我做错了什么?

解决

问题是insertBefore函数的参数2必须是节点,而不是字符串。解决方案是:

master_parent.insertBefore(create_element, main.page.getElementById(selected));

0 个答案:

没有答案