从HTML DOM动态添加和删除元素

时间:2015-09-30 08:33:09

标签: jquery html dom tabs

我正在处理一个HTML页面,其中有一个表格中的项目列表,并且在单击项目时会生成一个新选项卡,显示所单击项目的详细信息。我正在使用jquery-ui标签来动态创建标签。只有当该项目不存在选项卡时,我才需要打开项目的选项卡。我使用下面的代码来实现这个

if(! $('#selector').length )
{
   //create new tab for the item
}

我为每个项目使用带唯一ID的标签。这个代码在第一次加载选项卡时有效,问题是我还有一个X按钮来关闭选项卡,然后单击该按钮我使用jquery .remove()函数从HTML DOM中删除选项卡分区。通过这种方式删除选项卡,但是当我尝试在删除一次后为特定项添加选项卡时。然后上面的代码不起作用,它表明选项卡已经存在。并且没有创建新选项卡。如何从HTML DOM中完全删除元素,以便上面的代码可以在删除一次后重新创建选项卡。在此先感谢您的任何帮助

<body>
    <div id='tabs'>

        <ul>

        </ul>

    </div>
</body>
<script>
    $(document).ready(function(){ 

        $("#tabs").tabs();

        $(document).on('click', '.clickable_sellername', function(){

            debugger;
            var sellerid = parseInt(this.id.split('_')[2]);
            var sellername = $(this).text();

            if($('#tabindex_'+sellerid).length == 0){

                $.ajax({
                    type:"GET",
                    url :"/myadmin/loadprofile",
                    data:{ 'sellerid':sellerid },
                    dataType:"html",
                    success: function(data){

                        // Add a new tab
                        $("#tabs ul").append("<li id='tabindex_"+sellerid+"' ><a href='#sellertab_" + sellerid + "'>" +  sellername + "</a><a href='#' id='close_"+sellerid + "' class='ui-tabs-anchor remove' role='presentation' >x</a></li>");

                        // Add content to the newly added tab
                        $("#tabs").append("<div id='sellertab_"+sellerid+"' ></div>");
                        $('#sellertab_'+sellerid).html(data)

                        // Refresh tabs to add newley added tab
                        $("#tabs").tabs("refresh");

                    }
                });
                return false;
            }
        });

        $(document).on('click', '.remove', function(){

            // Get the tab number of pressed close button
            var sellerid = parseInt(this.id.split("_")[1]);

            // Remove the tabindex
            $('#tabindex_'+sellerid).remove();

            // Remove the tab content
            $('#sellertab_'+sellerid).remove();

            //Refresh the tabs
            $('#tabs').tabs("refresh");

        });

    });

1 个答案:

答案 0 :(得分:0)

$('#selector').length 
即使在删除后,

也会为“list”元素返回非零值 它使用jquery .remove()来自DOM,而在“div”元素的情况下 使用.remove()删除div后,它为上面的表达式返回零。所以我使用“div”元素进行检查,即现在我使用

if($('#sellertab_'+sellerid).length == 0)

而不是

if($('#tabindex_'+sellerid).length == 0)