简体   繁体   中英

Working with DOM after AJAX call

I have this function:

$('body').on('click', '.kategorija_izbor ul a, .mali_oglas a[role=pretraga]', function(e){
        var mgl_wrapper = $('.mali_oglasi_wrapper'),
        mgl = $(".mali_oglasi"), 
        mgl_space =  $(this).attr('href').replace(/\s+/g, '-').toLowerCase();
        link = mgl_space + ' .mali_oglasi';         
        mgl.animate({'opacity' : 0}, 400, function(){
            mgl_wrapper.load(link, function(){
                mgl.animate({'opacity' : 1}, 400);
            });
        });
        e.preventDefault(); 
    });

It is working, but I would like to know is there another way to do it. It seems to me that this way is time consuming and resource inefficient. Every time page is clicked script is going through DOM and search for specific elements. Is there a way to store .kategorija_izbor ul a and .mali_oglas a[role=pretraga] (they are bout loaded via load function )?

EDIT I

.kategorija_izbor ul a and .mali_oglas a[role=pretraga] are children of mgl_wrapper *( $('.mali_oglasi_wrapper')) , and they are dynamically created every time they are clicked.

If the elements are only being loaded into mgl , just restrict the click handler's scope so jQuery doesn't have to search through the entire body :

var $mgl_wrapper = $('.mali_oglasi_wrapper');
var $mgl = $('.mali_oglasi');

$mgl.on('click', '.kategorija_izbor ul a, .mali_oglas a[role=pretraga]', function(e) {
    var mgl_space =  this.href.replace(/\s+/g, '-').toLowerCase();

    $mgl.animate({'opacity' : 0}, 400, function() {
        $mgl_wrapper.load(mgl_space + ' .mali_oglasi', function() {
            $mgl.animate({'opacity' : 1}, 400);
        });
    });

    e.preventDefault(); 
});

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