【发布时间】:2014-08-13 12:43:28
【问题描述】:
我使用以下内容获取 URL,例如domain.com/#2 然后我使用该片段将用户重定向到 domain.com/?page=2。
但是,有时可能只向用户显示一个哈希值而没有数字,或者我可能会在单击表单时在 URL 中使用关键字,例如/#反馈。
问题是这会导致我使用的代码出现问题。我如何修改提供的代码,使其仅在我希望 URL 的样子时才对 URL 起作用。
例如,一种方法是检查片段值是否为“反馈”,但我想为用户找到一种方法,可能输入一个值或一个奇怪的表单,只是创建一个空白片段值。
如果 URL 不包含 #(然后是数字)或给定的页面 ID,则不要执行任何操作。
所以网址:
domain.com/#2
将重定向到:
domain.com/?page=2
或者如果 URL 已经有一个 ?page=(number) ,它会将片段值添加到数字中:
domain.com/?page=2#2
将指向:
domain.com/?page=4
我最初认为它检查片段是否为数字,否则将其视为 0。
所以这个:
/*
Check if the URL has a # value. When a user visits a page from another / reloads the page and
it has a # fragment included, this code converts the # value and redirects the user to a page
such as domain.php?page=THE FRAGMENT VALUE
If the URL already contains a page value, it adds that value to the hash value and will
redirect the user to the new value page.
*/
// First get the page URL and split it via # and ? signs
var parts = location.href.split('#');
var queryParameters = location.search.split('?');
// Now we get the value of the page value in the URL if there is one
var pageNumber = 0;
for(var i = 0; i < queryParameters.length; i++)
{
var keyvaluePair = queryParameters[i].split('=');
if(keyvaluePair[0] == 'page')
{
pageNumber = keyvaluePair[1];
break;
}
}
// Next we check how many parts there are in the URL and if this a value, we add it to the current page
// and redirect to that new page number
if(parts.length > 1)
{
var params = parts[0].split('?');
var mark = '?';
if(params.length > 1)
{
mark = '?';
}
var newPageNumber = parseInt(parts[1], 10) + parseInt(pageNumber, 10);
location.href = mark + 'page=' + newPageNumber;
}
【问题讨论】:
-
你能给出预期/样本的“输入”和“输出”吗?
-
你试过
location.hash而不是在location.href上拆分吗? -
刚刚更新了一些我想要发生的事情/当前 URL 发生的事情的例子
标签: javascript php jquery url fragment