如果单击单选按钮,则在javascript中追加和删除子元素

时间:2017-03-28 13:04:17

标签: javascript html

我正在向select数据库编写代码,使用该数据库可以显示应该运行哪种类型的查询。我正在使用动态append()在select标签中添加查询,如果我更改单选按钮选项,则应更改选项,每次单击单选按钮时,都应删除上一个选择标记。我编写了代码,但它甚至没有附加select子节点。请帮忙 谢谢。

var container = document.getElementById("container");
            if(db == "user")
            {
                if(bookq==null)
                {
                    bookq = document.getElementById ("query2");
                    bookq.parentNode.removeChild (bookq);
                }
                var array = ["Show Database","Delete Record"];
                var selectList = document.createElement("select");
                selectList.id = "query1";
                container.appendChild(selectList);
                for (var i = 0; i < array.length; i++) 
                {
                    var option = document.createElement("option");
                    option.value = array[i];
                    option.text = array[i];
                    selectList.appendChild(option);
                }
                userq=null;
            }
            else 
            {
                if(userq==null)
                {
                    userq = document.getElementById ("query1");
                    userq.parentNode.removeChild (userq);
                }
                var array = ["Show Database","Delete Record","Insert Record"];
                var selectList = document.createElement("select");
                selectList.id = "query2";
                container.appendChild(selectList);
                for (var i = 0; i < array.length; i++) 
                {
                    var option = document.createElement("option");
                    option.value = array[i];
                    option.text = array[i];
                    selectList.appendChild(option);
                }
                bookq=null;
            }

1 个答案:

答案 0 :(得分:0)

将代码包装在

之间
window.onload = function(){
  //  your code goes here
}

这将确保加载DOM对象并为javascript调用做好准备。