URL可以告诉jQuery运行一个函数吗?

Ila*_*sda 4 jquery jquery-selectors

有关于URL和jQuery的问题.

我可以指定URL来告诉jQuery运行一个函数吗?

例如http://www.website.com/about.html?XYZ

运行功能XYZ();

jfr*_*d00 9

您可以将代码放在该网页中,该网页检查URL上的查询参数,然后根据它找到的内容调用您想要的任何javascript函数.

在您的特定示例中,简化版本将如下所示:

// code that runs when page is loaded:
if (window.location.search == "?XYZ") {
    XYZ();
}
Run Code Online (Sandbox Code Playgroud)

或者如果你想让它运行那里存在的任何函数,你可以从字符串中提取它并运行那里的任何名称.

// code that runs when page is loaded:
if (window.location.search.length > 1) {
    var f = window.location.search.substr(1);  // strip off leading ?
    try {
        eval(f + "()");  // be careful here, this allows injection of javascript into your page
    } catch(e) {/* handler errors here */}
}
Run Code Online (Sandbox Code Playgroud)

允许在您的页面中运行任意javascript可能会或可能不会产生不良安全隐患.如果可能的话,最好只支持一组特定的预先存在的函数,这些函数是你所寻找和知道的,而不是像第二个例子那样执行任意的javascript.