单击按钮时,我想在当前选定元素之前插入一个元素。我通过将最后点击的元素 ID 存储在变量中来处理“选定”。
我的代码:
初始化.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));