使用JavaScript搜索URL的哈希值,而不是特定的字符串

Using JavaScript to search the URL for hash, not a specific string though

本文关键字:字符串 JavaScript 搜索 URL 哈希值 使用      更新时间:2023-09-26

我正在寻找一种方法来搜索页面的URL,在搜索中寻找特定的关键字。

例如,如果哈希值"/three"存在,我想运行一个JavaScript函数。但问题是,我有8个哈希值,它们可以以任何特定的顺序被触发。

这意味着我不能这样做-

<script>
        window.onhashchange = function(){
  switch(location.hash) {
    case '#hide':
      javascript:alert("Find a valid NFC tag to continue!")
    break;
    case '#hide/one':
      javascript:alert("You found piece number one!")
    break;
    case '#hide/two':
      javascript:alert("You found piece number two!")
    break;
    case '#hide/three':
      javascript:alert("You found piece number three!")
    break;
    case '#hide/four':
      javascript:alert("You found piece number four!")
    break;
    case '#hide/five':
      javascript:alert("You found piece number five!")
    break;
    case '#hide/six':
      javascript:alert("You found piece number six!")
    break;
    case '#hide/seven':
      javascript:alert("You found piece number seven")
    break;
    case '#hide/eight':
      javascript:alert("You found piece number eight!")
    break;
  }
}
        </script>

,因为URL最终可能是"example.com/index.html#hide/one/five/three/etc.."。它现在的配置方式是,它会专门搜索"#hide/one","#hide/two"等。

但是"#hide"不是插入到每个散列中,只插入到第一个散列中。所以永远不会有"#hide/one/#hide/two等"。

我需要弄清楚如何在URL中搜索"一"、"二"、"三"等,并相应地执行功能。

提前感谢,期待了解更多关于这一点!

编辑-只要阅读我的帖子,我觉得我应该澄清一些事情。知道JavaScript函数"hash。length"吧?比如"hash"。长度",但对于内容,如"哈希"。内容之类的东西会很棒。但我认为这是不存在的。

-Mitchyl

var hashArray = location.hash.substr(1).split('/'); // substr(1) skips over the # at the beginning
if (hashArray.indexOf('hide') != -1) {
    if (hashArray.indexOf('one') != -1) {
        alert("You found piece number one");
    } else if (hashArray.indexOf('two') != -1) {
        alert("You found piece number two");
    } ...
}

顺便说一句,在调用alert()之前不需要标记javascript:。你需要javascript:的唯一时间是当你把一个脚本在HTML属性,通常包含一个URL,例如hrefsrc属性-它采取的地方像http:告诉它运行代码,而不是下载一个文档。

它在这个DEMO中工作。点击链接后,编辑URL并将one更改为two,您将收到警报。

这个比较动态

你只需要改变第一个变量"aHash",其余的将自动构建。顺便说一句,这只是必要的,以防止脚本对用户本身的哈希操作的反应。否则,你可以只迭代拆分的哈希字符串,但这很容易出错。

// here goes the configuration
// if you want to change the "keys" here's the right place
// therefor it's better maintainable
var aHash = ['one', 'two', 'three'];
// autobuild an object with values as keys from given array at the top
var oHash = {},
    i     = aHash.length;
// don't forget that iteration usually starts with [0] but if you get the length will be 1 if one element is available
while( i-- )
{
  oHash[ aHash[ i ] ] = null;
}

window.onhashchange = function()
{
  // split hash into pieces into an array
  aHash  = document.location.hash.split('/');
  var iL = aHash.length;
  // workaround for case: '#hide/'
  if (aHash[ iL-1 ] === '')
  {
    --iL;
  }
  if (iL == 1 && aHash[0] === '#hide')
  {
    alert ('Find a valid NFC tag to continue!');
    return;
  }
  // only needed if one wants to collect the result
  var sAlert = '';
  // iterate from left to right in hash
  // if this isn't nessecary one can use the same while structure like at the beginning (without iL)
  i = -1;
  while( ++i < iL )
  {
    if (oHash[ aHash[ i ] ] === null )
    {
      // alert every time
      alert( 'You found piece number ' + aHash[ i ] + '!' );
      // colect for alert
      sAlert += aHash[ i ] + ' and ';
    }
  }
  if (sAlert !== '')
  {
    alert( 'You found pieces number ' + sAlert.substr( 0, sAlert.length-5 ) + '!' );
  }
}

如果您想测试哈希是否以#hash开头,并且哈希路径中是否存在数字,那么您可以试试这个

window.onhashchange = function() {
    if (location.hash.indexOf('#hash') !== 0) {
        return;
    }
    location.split('/').forEach(function(num) {
        switch (num) {
            case 'one':
                alert("You found piece number one!");
                break;
            // ...
            case 'eight':
                alert("You found piece number eight!");
                break;
        }
    });
}

请注意,这在IE7或IE8中不起作用