问题
Have a question regarding URL and jQuery.
Can I specify URL to tell jQuery to run a function?
e.g http://www.website.com/about.html?XYZ
to run a function XYZ();
?
回答1:
You can put code in that web page that examines the query parameters on the URL and then, based on what it finds, calls any javascript function you want.
In your particular example, a simplified version would be like this:
// code that runs when page is loaded:
if (window.location.search == "?XYZ") {
XYZ();
}
or if you want it to run any function that is present there, you can extract that from the string and run whatever name is there.
// 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 */}
}
Allowing arbitrary javascript to be run in your page may or may not have undesirable security implications. It would be better (if possible) to support only a specific set of pre-existing functions that you look for and know are safe rather than executing arbitrary javascript like the second example.
回答2:
In the URL bar you can always put javascript:XYZ();
Try that after this url loads: http://jsfiddle.net/maniator/mmAxY/show/
回答3:
I believe so:
if(location.href == ""){
xyz();
else{
}
回答4:
You can call a globally declared function using the window object:
function bar(str) {
alert("hello" + str);
}
// assuming location is "http://example.com?bar"
var fn = window.location.search.replace("?", "");
window[fn](" Dovhakiin"); // 'hello Dovhakiin'
来源:https://stackoverflow.com/questions/6736248/can-url-tell-jquery-to-run-a-function