jQuery 从 url 获取参数然后做一些事情

jQuery grab param from url then do stuff

我正在努力处理一个脚本,这让我头疼不已。我有一个站点,您可以在其中单击移动版本的 "full site" 的 link 以剥离移动样式并加载幻灯片中的所有幻灯片。对于您所在的任何页面,link 只是“?mobile=off”。所以我正在编写一个脚本来从 URL 中获取该参数,然后有一个 if else 语句。这是我所拥有的,但它不起作用。即使满足正确的条件,它也总是转到语句的 else 部分,所以我认为它不会在 if 语句中获取参数值。如果我只使用 if (Modernizr.mq'(max-width: 1000px)')) 没有 urlParams 在那个 if 语句中,它确实有效。

var urlParams;
(window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();


if ( (Modernizr.mq('(max-width: 1000px)')) && (urlParams[mobile] == ('undefined')) ) { 
        //this stuff removes all except first slide in flexslider for mobile
        $(".flexslider li:not(.keep)").remove();
        $( ".flexslider" ).removeClass( "flexslider loading" ).addClass( "noslider" );
        $( ".slides" ).removeClass( "slides" ).addClass( "noslides" );

} else {
      //strips off mobile stylesheet and loads all flexslider slides
      $("#mobile").remove();
      $(window).load(function(){
      $('.flexslider').flexslider({
        animation: "fade",
    animationSpeed: 3500,
    directionNav: false,
    controlNav: false,
    smoothHeight: false,
    slideshow: false,
    useCss: false,
        start: function(slider){
          $('body').removeClass('loading');
        }
      });
    });

$('.prev, .next').on('click', function(){
    var href = $(this).attr('href');
    $('.flexslider').flexslider(href)
    return false;
});
}

将您的 if 语句更改为:

if ( (Modernizr.mq('(max-width: 1000px)')) && (urlParams[mobile] === undefined) ) { 

你也可以这样做:

if ( (Modernizr.mq('(max-width: 1000px)')) && (typeof(urlParams[mobile]) == 'undefined') ) {