简体   繁体   English

使用jQuery删除动态生成的div

[英]Remove dynamically generated div with jquery

I would like to add/remove a new div when the corresponding checkbox is checked/unchecked with jQuery. 我想在使用jQuery选中/取消选中相应复选框时添加/删除新的div。 Here's my attempt: 这是我的尝试:

<script type="text/javascript">
    $(function() {
        $("#form1 :checkbox#checkbox1").click(function() {
            var d = document.createElement('div');
            if ($(this).is(":checked")) {
                $(d).addClass("newdiv")
                    .html("This is a new div")
                    .appendTo($("#mydiv"))
                    .hide()
                    .fadeIn(1000);
                }
            else {
                //$(".newdiv").fadeOut(1000);
                $(d).fadeOut(1000);
            }
        });
    });
</script>

The fadeIn process comes out smoothly. fadeIn过程顺利进行。 But when I tried to fadeOut $(d) using the same methodology, it didn't work: the new generated div remained on the page. 但是,当我尝试使用相同的方法淡出$(d)时,该方法不起作用:新生成的div仍保留在页面上。 I did some research and get a work around, with $(".newdiv").fadeOut(1000); 我做了一些研究,并使用$(".newdiv").fadeOut(1000); (commented in the code above), but that's not the best solution for me I think. (在上面的代码中进行了评论),但是我认为这对我来说不是最佳解决方案。 And also I really want to know why my first attempt didn't work. 而且我真的很想知道为什么我的第一次尝试不起作用。 Any suggestions? 有什么建议么? Thanks. 谢谢。

There are few changes you can make 您可以进行的更改很少
1. No need for the selector #form1 :checkbox#checkbox1 since you have an id for the checkbox, you can just use #checkbox1 1.无需选择器#form1 :checkbox#checkbox1因为您具有#form1 :checkbox#checkbox1的ID,因此您可以使用#checkbox1
2. Create the div using jQuery instead of using createElement $('<div/>') 2.使用jQuery而不是使用createElement $('<div/>')创建div
3. After fading out the div you need to remove it from the dom 3.淡出div后,您需要将其从dom中删除

$(function() {
    $("#checkbox1").click(function() {
        if ($(this).is(":checked")) {
            $('<div/>').addClass("newdiv")
            .html("This is a new div")
            .appendTo($("#mydiv"))
            .hide()
            .fadeIn(1000);
        }
        else {
            $('#mydiv .newdiv').fadeOut(function(){
                $(this).remove()
            })
        }
    });
});

Demo: Fiddle 演示: 小提琴

Another solution is to have a static div which will be shown and hidden 另一个解决方案是让静态div显示和隐藏

$(function() {
    var div = $('<div/>').addClass("newdiv")
            .html("This is a new div")
            .appendTo($("#mydiv"))
            .hide();
    $("#checkbox1").click(function() {
        if ($(this).is(":checked")) {
            div.fadeIn(1000);
        } else {
            div.fadeOut(1000)
        }
    });
});

Demo: Fiddle 演示: 小提琴

jsFiddle Demo jsFiddle演示

Every time your click handler runs, you're creating a new variable d with a new element. 每次您的点击处理程序运行时,您都会使用新元素创建一个新变量d Instead, do that before the click handler, so each instance will reference the same element. 而是在单击处理程序之前执行此操作,以便每个实例将引用相同的元素。 I have included other optional improvements below. 我在下面包括了其他可选的改进。

A change event is more appropriate for checkboxes. change事件更适合复选框。 Also, notice I made your selector just #checkbox1 , since that is already unambiguous and maximally specific. 另外,请注意,我使您的选择器只是#checkbox1 ,因为这已经是明确的并且是最大的。

To get a better visual effect, don't add the element, hide it, then fade it in. In most browsers that will show the element flicker before it appears. 为了获得更好的视觉效果,请不要添加元素,先将其隐藏,然后使其淡入。在大多数浏览器中,该元素在出现之前都会先闪烁。 Instead, use a class to hide it with css: .hidden {display: none;} . 而是使用类通过css: .hidden {display: none;}来隐藏它。 You can also use fadeToggle to toggle the visibility, instead of doing if/else. 您也可以使用fadeToggle切换可见性,而不是执行if / else。 clearQueue removes extra events for multiple clicks during a transition, and makes transitions appear smoother. clearQueue删除过渡期间多次单击的额外事件,并使过渡看起来更平滑。

Finally, use jQuery to create the element: 最后,使用jQuery创建元素:

$(function () {
    var $d = $('<div>', {
        "class": "hidden",
        text: "This is a new div"
    }).appendTo("#mydiv");

    $("#checkbox1").change(function () {
        $d.clearQueue()
          .stop()
          .fadeToggle(1000);
    });
});

You better make da jQuery object. 您最好制作一个jQuery对象。

<script type="text/javascript">
    $(function() {
        $("#checkbox1").click(function() {
            var d = $('<div class="newdiv"></div>');
            if ($(this).is(":checked")) {
                d.html("This is a new div")
                .appendTo($("#mydiv"))
                .hide()
                .fadeIn(1000);
                }
            else {
                d.fadeOut(1000);
            }
        });
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM