开发者

Remove a div with jQuery

开发者 https://www.devze.com 2022-12-13 08:45 出处:网络
I have this code currently in one of my websites, $(\"a.navlink\").click(function (ev) { ev.preventDefault();

I have this code currently in one of my websites,

$("a.navlink").click(function (ev) {
                ev.preventDefault();
                var id = $(this).attr("id")
                if($(this).hasClass("active")) {
                    alert(id);
                    $(id).remove("<div id="+ id +"/>");
                }
            $(this).toggleClass("active");
               var url开发者_开发知识库 = $(this).attr("href");
                $.ajax ({
                    url: "index.php/home/category",
                    type: "GET",
                    success : function (html) {
                //alert("Success");
                        $("#accordion").append($("<div id="+ id +"/>").append(html)
                        );
                    }
                });
            });

Essentially what is does it gets the ID from the click nav and gets some data from the database and then places that data in a div that is uniquely named with the ID of the click element. What I want to know is how could then remove the div element that is created on the fly, as you can see from my code I have given it try.


You have another problem with your code. You are attempting to give the DIV the same ID as the link. IDs need to be unique so this results in invalid HTML. Try prepending "div_" to the link's id, then use:

 $('#div_' + id).remove();

resulting in:

$("a.navlink").click(function (ev) {
    var id = $(this).attr("id");
    if($(this).hasClass("active")) {
        alert(id);
        $('#div_' + id).remove();
    }
    $(this).toggleClass("active");
    var url = $(this).attr("href");
    $.ajax ({
        url: "index.php/home/category",
        type: "GET",
        success : function (html) {
            //alert("Success");
            $("#accordion").append($("<div id='div_"+ id +"'/>").append(html));
        }
    });
});


if ($(this).hasClass("active")) {
   $(this).remove();
}

Is all you need!

0

精彩评论

暂无评论...
验证码 换一张
取 消