如何使用onclick javascript动态添加,删除列表中的节点

How to dynamicallly add, delete node in list using onclick javascript

本文关键字:列表 删除列 节点 删除 onclick 何使用 javascript 动态 添加      更新时间:2023-09-26

我希望每个文件夹旁边有 2 张图像。第 1 张图像,单击该图像时可以创建其子文件夹。第 2 张图像,单击哪个文件夹本身及其所有子文件夹被删除

这是我的代码。它可以创建子文件夹,但不能删除。我是JavaScript的新手...帮帮我

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Javascript Directory code</title>
<style>
ul 
{
list-style-image:url('closed.gif');
}
</style>

</head>
<body>
<ul>
    <li onClick="myFunction.call(this, event)" id="root">Root</li>
</ul>

<script language="javascript" type="text/javascript">
function myFunction(e)
{
    e.stopPropagation();
    var id=prompt("Enter Folder id");
    if (id != '' && id != null)
    {
        var val=prompt("Enter Folder name");
    }
    if (id != '' && id != null && val !='' && val !=null) 
    {
        var ulnode=document.createElement("UL"); //new ul<br>
        var node=document.createElement("LI"); //new li<br>
        node.id = id;//set id of new li <br>
        node.onclick = myFunction;//set onclick event of new li<br> 
        var textnode=document.createTextNode(val);//li value<br>
        node.appendChild(textnode);// new li + li value<br>
        ulnode.appendChild(node);// ul + li value
        this.appendChild(ulnode);
    }
}
</script>
</body>
</html>

这可能有效:

        function myFunction(e)
        {
            e.stopPropagation();
            var id=prompt("Enter Folder id");
            if (id != '' && id != null)
            {
                var val=prompt("Enter Folder name");
            }
            if (id != '' && id != null && val !='' && val !=null) 
            {
                var ulnode=document.createElement("UL"); //new ul<br>
                var node=document.createElement("LI"); //new li<br>
                node.id = id;//set id of new li <br>
                node.onclick = myFunction;//set onclick event of new li<br>
                var anc=document.createElement("A"); //new li<br>
                anc.innerHTML = "---";
                anc.onclick = deleteNode;
                node.appendChild(anc);// new li + li value<br>);// new li + li value<br>
                var textnode=document.createTextNode(val);//li value<br>
                node.appendChild(textnode);// new li + li value<br>
                ulnode.appendChild(node);// ul + li value
                this.appendChild(ulnode);
            }
        }
        function deleteNode(e){
            e.stopPropagation();
            var caller = e.target || e.srcElement;
            var childToRemove = caller.parentNode.parentNode;
            childToRemove.parentNode.removeChild(childToRemove);
        }

如果你要使用jQuery,你可以在函数中使用$('#id-of-folder').remove();将其从DOM中删除。