简体   繁体   English

将哈希网址解析为JavaScript中的对象?

[英]Parsing hash url to object in JavaScript?

I would like to execute a process on the page load depending on what the hash in the URL is. 我想根据URL中的哈希值在页面加载时执行一个过程。 I think I will need RegEx because I am looking for a pure JavaScript solution (no library dependencies). 我想我将需要RegEx,因为我正在寻找纯JavaScript解决方案(无库依赖项)。

What I am trying to do is if the hash is "#/products", then I will call "myIndex()" else if the hash is "#/products/3", then I will call "myDetail(id)" where "id" is a variable to the product number. 我想做的是,如果哈希为“#/ products”,那么我将调用“ myIndex()”;否则,如果哈希为“#/ products / 3”,那么我将称为“ myDetail(id)”,其中“ id”是产品编号的变量。

Anybody have a good idea on how to achieve this? 有人对如何实现这一目标有一个好主意吗?

Here's a solution that checks for the literal string '#/products' first, avoiding the regular expression where it's unnecessary. 这是一个先检查文字字符串'#/products'的解决方案,避免在不需要时使用正则表达式。

var hash = location.hash,
    regexID = /^#\/products\/(\d+)$/,
    matches;

if (hash == '#/products') {
  myIndex();
} else if (matches = hash.match(regexID)) {
  myDetail(matches[1]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM