如何在URL中添加一个参数,以触发jQuery在加载时运行函数

How to add a param to a URL that trigger jQuery to run a function on load

本文关键字:jQuery 加载 函数 运行 参数 一个 URL 添加      更新时间:2023-09-26

有没有一种方法可以添加url参数,比如:http://site.com?open=true

在文档就绪时,如果jQuery看到open param设置为true,是否执行函数?

感谢

首先让我们在JS 中制作一个好的查询字符串搜索器

function querySt(qsName, url)
        {
            var theUrl;
            if (url == null || url == undefined)
                theUrl = window.location.search.substring(1); else theUrl = url;
            var g = theUrl.split("&");
            for (var i = 0; i < g.length; i++) {
                var pair = g[i].split("=");
                if (pair[0].toLowerCase() == qsName.toLowerCase())
                {
                    return pair[1];
                }
            }
            return null;
        }

$(function (){
  if (querySt("open")!='true') return;
});

取自网站http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/

function $_GET(q,s) { 
    s = s ? s : window.location.search; 
    var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i'); 
    return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined; 
}  

您可以使用正则表达式测试location.href

if (location.href.match(/open=true/)
    // do something

不过,您可能需要使用regex,以确保它适用于您。