简体   繁体   中英

How can I observe changes to my DOM and react to them with jQuery?

I have this function where I toggle a class on click, but also append HTML to an element, still based on that click.

The problem is that now, I'm not listening to any DOM changes at all, so, once I do my first click, yup, my content will be added, but if I click once again - the content gets added again, because as far as this instance of jQuery is aware, the element is not there.

Here's my code:

(function($) {
    "use strict";

    var closePluginsList = $('#go-back-to-setup-all');
    var wrapper = $('.dynamic-container');

    $('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
        $('.setup-theme-container').toggleClass('plugins-list-enabled');

        if ( !wrapper.has('.plugins-container') ){
            var markup = generate_plugins_list_markup();
            wrapper.append(markup);
        } else {
            $('.plugins-container').hide();
        }
    });


    //Below here, there's a lot of code that gets put into the markup variable. It's just generating the HTML I'm adding.
})(jQuery);

Someone suggested using data attributes, but I've no idea how to make them work in this situation.

Any ideas?

You could just do something like adding a flag and check for it before adding your markup.

    var flag = 0;
    $('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
    $('.setup-theme-container').toggleClass('plugins-list-enabled');


    if ( !wrapper.has('.plugins-container') ){
        var markup = generate_plugins_list_markup();
        if(flag == 0){
            wrapper.append(markup);
            flag = 1;
        }

    } else {
        $('.plugins-container').hide();
    }
});

If you want to add element once only on click then you should make use of .one() and put logic you want to execute once only in that handler.

Example :

$(document).ready(function(){
    $("p").one("click", function(){
       //this will get execute once only
        $(this).animate({fontSize: "+=6px"});
    });

    $("p").on("click", function(){
      //this get execute multiple times 
        alert('test');
    });
});

html

<p>Click any p element to increase its text size. The event will only trigger once for each p element.</p>

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