2012-10-30 43 views
5

前我已經在MVC3查看下面的代碼:window.location.hash返回散列標籤中的值

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

     manager.doSomeStuff(window.location.hash); 
    } 
}); 

有趣的是,當有在URL中沒有散列標籤,或只存在一個散列標籤例如:

http://localhost:1223/Index/AboutUs 

http://localhost:1223/Index/AboutUs# 

window.location.hash是空的,並且不執行該功能。 但是,當有哈希標籤的一些值:

http://localhost:1223/Index/AboutUs#categoryId=5&manufacturerId=8 

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

你能向我解釋爲什麼#標籤包含在價值以及爲什麼在沒有值#標記後,window.location.hash爲空。

+0

是的嗎? – adeneo

回答

9

沒有什麼可以解釋的。這是它的工作方式。

更多在這裏閱讀:http://www.w3schools.com/jsref/prop_loc_hash.asp

定義和用法

The hash property returns the anchor portion of a URL, including the hash sign (#). 
+0

是的,我看到了定義,但似乎奇怪的是,散列符號與該值一起返回。這就是我問這個問題的原因。另外,當您設置window.location.hash值時,您不需要將該散列符號添加到該字符串。 –

8

你可以改變它,如果你想通過簡單地改變哈希名稱:

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

//Your new hash name without "#" 
var newHashName = nameHash.replace("#",""); 
+0

如果哈希包含另一個'#'字符,這可能會產生不良結果。 – Bernard

1

You can repalce #但這種方式會產生衝突,不會與JavaScript一起工作。

Here is window.location reference link.

下面是不同的使用的例子:

$(document).ready(function() { 
    var urlHash = window.location.hash; 
    var sampleURL = '#categoryId=5&manufacturerId=8'; 

    if (urlHash.length > 1) { 
     //do stuff 
    }else{ 
     //if value is empty, do stuff 
    } 

    if (urlHash === sampleURL) { 
     commonResponse(); 
    } 

    $('a').click(function() { 
     var target = $(this).attr('href'); 

     if (target === sampleURL) { 
      commonResponse(); 
     }  
    }); 

    function commonResponse() { 
     //alert('ok'); 
    } 
}); 
7
var hash = window.location.hash.substring(1); 

此省略了串,這是散列標籤的第一個字符。