How to attach a event to a jQuery mobile page using on() and off()?

淺唱寂寞╮ 提交于 2019-11-29 12:38:56

You should be able to use $.on() to bind to all pages, as well as specific pages. I've created a sample here http://jsfiddle.net/kiliman/aAanV/

I've added a pageinit/pageshow handler for ALL pages (to show that pageinit fires once per page, and pageshow fires each time page is shown). I then create a pageinit handler for #page1 to bind a click event handler on a button.

Notice the syntax. $(elements).on('events', 'selector', handler) vs $(elements).on('events', handler);

If you include the selector, then you are delegating the handler to all elements that match the selector. If you DON'T include the selector, then you are binding the handler directly to the elements.

$(function() {
    // setup init/show handler for ALL pages
    var selector = ':jqmData(role=page)';
    $('body')
        .on('pageinit', selector, function(e, data) {
            // initialize page
            var $page = $(this);
            alert('init ' + $page.attr('id'));
        })
        .on('pageshow', selector, function(e, data) {
            // showpage
            var $page = $(this);
            alert('show ' + $page.attr('id'));
        });
    // setup init handler for page1
    $('#page1').on('pageinit', function(e, data) {
        // setup handler
        var $page = $(this);
        $page.find('.colorchanger').click(function() {
            var $content = $page.find('.ui-content'),
                isBodyC = $content.hasClass('ui-body-c');
            $content
                .toggleClass('ui-body-c', !isBodyC)
                .toggleClass('ui-body-e', isBodyC);
        });

    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!