URL可以告诉jQuery运行一个函数吗?
有关于URL和jQuery的问题。
我可以指定URL来告诉jQuery运行一个函数吗?
例如http://www.website.com/about.html?XYZ
运行函数XYZ();
?
您可以将代码放在该网页中,该网页检查URL上的查询参数,然后根据它找到的内容调用您想要的任何javascript函数。
在您的特定示例中,简化版本将如下所示:
// code that runs when page is loaded: if (window.location.search == "?XYZ") { XYZ(); }
或者如果你想让它运行那里存在的任何函数,你可以从字符串中提取它并运行那里的任何名称。
// 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 */} }
允许在您的页面中运行任意javascript可能会或可能不会产生不良安全隐患。 如果可能的话,最好只支持一组特定的预先存在的函数,这些函数是您查找并知道的,而不是像第二个例子那样执行任意的javascript。
在URL栏中,您始终可以输入javascript:XYZ();
在此url加载后尝试: http : //jsfiddle.net/maniator/mmAxY/show/
我相信是这样:
if(location.href == ""){ xyz(); else{ }
您可以使用window对象调用全局声明的函数:
function bar(str) { alert("hello" + str); } // assuming location is "http://example.com?bar" var fn = window.location.search.replace("?", ""); window[fn](" Dovhakiin"); // 'hello Dovhakiin'