jquery 移动 toPage select 属性不起作用

jquery mobile toPage select attribute doesn't work

我有一个带有一些页面的 jquery 移动应用程序。第一页是登录页面,用户登录后我不希望用户再次返回登录页面。

用户登录后 div 将显示名为 #map。

要防止这种情况,请使用以下代码:

$(document).on('pagecontainerbeforechange', function (e, ui) {

    var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage');

    if(activePage.attr('id') === 'map') {

        var test = ui.toPage;

        console.log(test.attr('id');

        // if(test.attr('id') === 'login' && login.status === true) {
        //  console.log('you are alrady logged in');
        //  e.preventDefault();
        //  e.stopPropagation();
        // }
    }
});

当我再次单击上一页转到登录页面时,出现此错误:Uncaught TypeError: test.attr is not a function

有什么问题,我怎么能 select 测试的 attr id

有时 ui.toPage 是字符串,有时是表示页面的 jQuery 对象。有时 pagecontainerbeforechange 会运行两次,一次使用字符串,一次使用对象。所以试试这个:

$( document ).on( "pagecontainerbeforechange", function( e, ui ) {
    var from = ui.prevPage ? ui.prevPage.prop("id") : '';
    var to = '';
    if (typeof ui.toPage === 'string') {
        var u = $.mobile.path.parseUrl(ui.toPage);
        to = u.hash || '#' + u.pathname.substring(1);
    } else {
        to = '#' + ui.toPage.prop("id");
    }

  if (from === 'map' && to === '#login') {
      alert('Cannot change to login from map');
      e.preventDefault();
           // remove active class on button
            // otherwise button would remain highlighted
      $.mobile.activePage
                .find('.ui-btn-active')
                .removeClass('ui-btn-active');
   }                
});

DEMO

此外,.attr("id") 会起作用,但在较新版本的 jQuery 中,使用 .prop("id") 更正确:http://api.jquery.com/prop/