简体   繁体   中英

Append HTML to div using jQuery when content is duplicated via JS

I'm appending some HTML from another div created via JavaScript - the first time I append the HTML everything works fine, but when I append the HTML again it adds the content twice, I guess because it's appending the HTML from both divs created via JS, and if I append it again it adds three copies, then four etc.

I've created a JSFiddle to show the problem: https://jsfiddle.net/49q0369a/

1.) Click "Pricing Per Night"

2.) Click "Seasonal Pricing"

3.) Click "Add Seasonal Price Filter" and then "Add Price Rule" (everything is working fine here)

4.) Click "Add Seasonal Price Filter" and then "Add Price Rule" again (still working fine)

5.) Now for the first "Seasonal Filter #1" click "Add Price Rule" again and you'll see it adds two price rule divs instead of one (this is the problem, is should always only add one)

The function which adds the price rule:

function add_price_rule() {
        $(".add-price-rule").on( "click", function() {
            $(this).parent().find(".price-rule-wrapper-outer").append($(".price-rule-wrapper").html());
            remove_price_rule();
            recacluclate();
        });
    }

Any direction as to how to solve this appreciated!

When Add seasonal price filter is selected the following code gets executed

$(".add-price-rule-season").on( "click", function() {
  ...
}

This adds an event listener to the Add Price Rule button.

When the Add seasonal price filter is selected again a new event listener gets added to the Add Price Rule button again. So, now there are two events associated with the button. As there are two events (both pointing to same method) on the button the method gets executed twice (and thus two sections gets added).

The same is applicable for other buttons. To demonstrate this I've added some console.log in the jsFiddle here . Select Add Price Rule multiple (say 3) times and then select Remove Price filter for each rule. Observe console. You will see that when any Remove Price Filter is selected for first time the method (event) gets executed once. When the next remove button is selected the event is executed twice and so on.

I prefer to fix this using the jQuery off event. The corresponding code would now look like the following

$(".add-price-rule-season").off().on( "click", function() {
  ...
}

This is demonstrated in the jsFiddle here .

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