简体   繁体   中英

Remove from inside div using jQuery

I have written a script that is supposed to render text (later a partial view) inside a div on click. I detect if div is visible or not and if not, I add text on click and make the div visible. This part works perfectly. When clicked and the div is visible I want to remove what has been added so that it wont multiply if I click it multiple times.

I get both alert - so detection of div visibility works but the text is not removed and it multiplies if I click it many times.

Here is my code - can you tell me what i am doing wrong?

<script language="javascript">
    $(document).ready(function () {
        $(".content").hide();
        $(".heading").click(function () {
            var id = $(this).attr("id");
            var content = $(this).next(".content");

            if (content.is(":hidden")) {
                content.append("<p id='render-object'>Testing rendering on click</p>");
                alert('Content is opening');
            }
            else if (content.is(":visible")) {
                content.next("#render-object").remove();
                alert('Content is closing');
            }

            content.slideToggle(100);                
        });
    });
</script>

删除时,您可能希望使用.find()而不是.next()。

Use .html() instead of .append()

<script language="javascript">
    $(document).ready(function () {
        $(".content").hide();
        $(".heading").click(function () {
            var id = $(this).attr("id");
            var content = $(this).next(".content");

            if (content.is(":hidden")) {
                content.html("<p id='render-object'>Testing rendering on click</p>");
                alert('Content is opening');
            }
            else if (content.is(":visible")) {
                content.find("#render-object").remove();
                alert('Content is closing');
            }

            content.slideToggle(100);                
        });
    });
</script>

Edit : - use .find() instead of .next() as render-object is child of content and not sibling

use .find instead of .next and use .html instead of .append

<script language="javascript">
$(document).ready(function () {
    $(".content").hide();
    $(".heading").click(function () {
        var id = $(this).attr("id");
        var content = $(".content");

        if (content.is(":hidden")) {
            content.html("<p id='render-object'>Testing rendering on click</p>");
            alert('Content is opening');
        }
        else if (content.is(":visible")) {
            content.find("#render-object").remove();
            alert('Content is closing');
        }

        content.slideToggle(100);                
    });
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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