简体   繁体   中英

How removing an appended element after a DIV is toggled using JQuery?

I have to append an element on a DIV that has toggle function. But when I click on toggle again(when it is toggled) the element that I appended previously is appended again. And I end up with two equal elements.

Observation: Consider that I need to append more than one element. And remove more than one element appended too.

Example:

DIV A
Element A

My actions in Javascript using JQuery:
1) Toggle DIV A and Append Element A = div A and element A show up.
2) Toggle DIV A = div A and element A disappear.
3) Toggle DIV A and Append Element A again =

DIV A
   Element A
   Element A      

I want only one Element A.(That's the problem, toggle doesn't remove my previous appended element)

My code is something like that:

$("#DIVA").toggle(function(){
    var my_div_to_be_appended = "<div>my div<div>";
    var my_div_to_be_appended2 = "<div>my div2<div>";
    $("DIVA").append(my_div_to_be_appended);
    $("DIVA").append(my_div_to_be_appended2);           
});

That's easy, instead of using append, use html.

$("#DIVA").toggle(function(){
    var my_div_to_be_appended = "<div>my div<div>";
    // This will replace the content every time the toogle function is called.
    $("DIVA").html(my_div_to_be_appended);            
});

If your DIVA is empty then sch4v4's solution is perfect for you, but if that div already has some content in it and you cannot use .html() then another simple solution to your problem is to keep another empty div inside of your $("#DIVA") instead of appending itself. Take the following example

<div id="DIVA">
  <!-- Some other elements here - if any -->
  <div id="my_dynamic_div"></div>
</div>

and then in your jquery code

$("#DIVA").toggle(function(){
    var my_div_to_be_appended = "<div>my div<div>";
    $("#my_dynamic_div").html(my_div_to_be_appended);            
});

Hope that helps.

Following the suggestions, for now, I'm doing this as a solution:

$("#DIVA").toggle(function(){
    var my_div_to_be_appended = "<div>my div<div>";
    var my_div_to_be_appended2 = "<div>my div2<div>";
    $("DIVA").html(my_div_to_be_appended + my_div_to_be_appended2);           
});

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