window.location.hash返回值前面的哈希标记

Iva*_*nov 5 javascript url jquery hashtag asp.net-mvc-3

我在MVC3视图中有以下代码:

 $(document).ready(function () {
    if (window.location.hash) {
        var manager= new Manager();

        manager.doSomeStuff(window.location.hash);
    }
});
Run Code Online (Sandbox Code Playgroud)

有趣的是,当URL中没有哈希标记时,或者只有哈希标记示例时:

http://localhost:1223/Index/AboutUs

http://localhost:1223/Index/AboutUs#
Run Code Online (Sandbox Code Playgroud)

如果window.location.hash为空并且未执行该功能.但是当哈希标记中有一些值时:

http://localhost:1223/Index/AboutUs#categoryId=5&manufacturerId=8
Run Code Online (Sandbox Code Playgroud)

中的值window.location.hash#categoryId=5&manufacturerId=8

你能解释一下为什么#标签包含在值中以及为什么#标签后面没有值时window.location.hash为空.

Pul*_*tal 9

没什么好解释的.这是它的工作方式.

在这里阅读更多内容:http://www.w3schools.com/jsref/prop_loc_hash.asp

定义和用法

The hash property returns the anchor portion of a URL, including the hash sign (#).
Run Code Online (Sandbox Code Playgroud)


小智 8

如果需要,只需更改哈希名称即可更改它:

//Your old hash name caught in a variable
var nameHash = location.hash;

//Your new hash name without "#"
var newHashName = nameHash.replace("#","");
Run Code Online (Sandbox Code Playgroud)

  • 如果散列包含另一个“#”字符,则可能会产生不良结果。 (2认同)

小智 7

var hash = window.location.hash.substring(1);
Run Code Online (Sandbox Code Playgroud)

这省略了字符串的第一个字符,即哈希标记.