Javascript 为页面链接使用url参数

Javascript 为页面链接使用url参数,javascript,html,variables,web,Javascript,Html,Variables,Web,我要问的可能听起来很愚蠢,但我已经想了好几天了。我要生成指向站点的链接: example.github.io/Example/Example 在它的末尾有一个变量或其他东西 example.github.io/Example/ExampleVariable 然后在页面加载时读取该变量。在一个完美的世界里,它看起来是这样的: http://Example.github.io/Example/Example<script>function(){}</script> ht

我要问的可能听起来很愚蠢,但我已经想了好几天了。我要生成指向站点的链接:

example.github.io/Example/Example
在它的末尾有一个变量或其他东西

example.github.io/Example/ExampleVariable
然后在页面加载时读取该变量。在一个完美的世界里,它看起来是这样的:

http://Example.github.io/Example/Example<script>function(){}</script>
http://Example.github.io/Example/Examplefunction(){}
我还需要确保用户实际访问或至少最终访问的页面是原始链接:即。
example.github.io/example/example

任何帮助都将不胜感激。


如果有人想知道
是的,如果适用,它在github上。我几乎不懂PHP,所以这不是最好的。这是我制作的待办事项列表管理器应用程序。有一个加载功能,用户可以共享列表。加载字符串(我试图读取的变量)如下所示:
/LoadNAME#THEME#项A、项B等。
如果您使用的是github页面,则可以使用。在这种情况下,url将如下所示:
http://mypage.github.io/test/?myparam=value


然后,您可以使用javascript查询,并根据url包含的url参数执行某些操作

或者,您可以使用这个hash
#
老把戏,然后在它使用斜杠之后

example.github.io/Example/#/var1/var2/var3
然后将
window.location.href
与耦合
split()
一起使用将为您提供 使用一组参数

/* URL in address bar: 
   http://localhost/test/js-url-parameters/#/str1/str2/str3/
*/

var docURL = window.location.href,
  params = [];

// filter out the website origin "example.github.io" in the OP example      
docURL = docURL.replace(window.location.origin, '');

// if /#/ found then we have URL parameters
// grabbing the parameters part of the URL
if (docURL.indexOf('/#/') > -1) {
  docURL = docURL.split('/#/')[1];
  if (docURL != '') {

    // omit the last forward slash if exist
    if (docURL[docURL.length - 1] == '/') {
      docURL = docURL.substring(0, docURL.length - 1);
    }

    // split the URL final string o get an object with all params 
    params = docURL.split('/');
    console.log(params);
  }
} else {
  console.log('No URL parameters found');
}

/* Output: 
   ["str1", "str2", "str3"]
*/


更新:

以上输出的所有变量均为
string
,因此要检索数值,需要根据具体情况选择
parseInt
-或
parseFloat()

例如,如果用于此URL:

http://localhost/test/js-url-parameters/#/str1/22/str3/
上面的代码将输出
[“str1”、“22”、“str3”]
,而我们假设将
22
作为整数,要解决此问题,只需添加以下内容:

// for each elements in params, if it is Not a Number (NaN) we return 
// it as it is, else it's a nubmer so we parseInt it then return it
for(var i in params){
    params[i] = isNaN(parseInt(params[i])) ? params[i] : parseInt(params[i]);
}
上面的代码片段位于
params=docURL.split('/')之后

现在,URL:

http://localhost/test/js-url-parameters/#/str1/22/str3/
输出
[“str1”,22,“str3”]
,正如您现在看到的
22
是一个数字而不是字符串


是的,它使URL看起来更好,更“友好”,但它将所有参数都作为
string
使用,因此您可能需要
parseInt()
数值