简体   繁体   中英

How to bind events to DOM elements that get refreshed

I have a BackboneJS site right now, but ran into a problem. I have one Backbone View that uses a jQuery.click() event handler. Right now, I have the handler set up globally inside the $(document).ready() function. However, I realized that if I load the page that uses the handler 1st, then everything works fine, but if I change pages (change the view that backbone displays) and then go back to the original page (refresh the DOM that uses the handler) then the events aren't triggered any more. How should I handle this? This must be a problem a lot of people run into so I would guess Backbone has a way to handle this.

Otherwise, My plan was to just call a function after the view is rendered to reset the handlers. Would this be the best way or does backbone have a way to handle this?

$(document).ready(function(){
    $('.section-pulldown').on('click', function(){
        var el = $(this).next();
        var par = $(this).parent();
        var arrow = $(this).children('img');

        if (el.css('display') == 'none') {
            el.css('padding-bottom', '50px');
            arrow.attr('src', 'images/downarrow.png');
            par.css('box-shadow', '0px 0px 15px 3px #A8A8A8 inset');
            $(this).next().slideToggle(700);

        }
        else {
            $(this).next().slideToggle(700, function(){
                el.css('padding-bottom', '0px');
                par.css('box-shadow', '2px 2px 15px 2px #CCCCCC inset');
                arrow.attr('src', 'images/uparrow.png');
            });

        }

    });
})

Try something like:

$(function() {
    $(document).on('click', '.section-pulldown', function(e) {
        var el = $(this).next();
        var par = $(this).parent();
        var arrow = $(this).children('img');

        if (el.css('display') == 'none') {
            el.css('padding-bottom', '50px');
            arrow.attr('src', 'images/downarrow.png');
            par.css('box-shadow', '0px 0px 15px 3px #A8A8A8 inset');
            $(this).next().slideToggle(700);

        }
        else {
            $(this).next().slideToggle(700, function(){
                el.css('padding-bottom', '0px');
                par.css('box-shadow', '2px 2px 15px 2px #CCCCCC inset');
                arrow.attr('src', 'images/uparrow.png');
            });

        }

    });
})

See jQuery .on as a delegate

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