2012-10-30 7 views
5

앞에 해시 태그를 반환 I 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 #하지만이 방법을 갈등을 일으키고 자바 스크립트로 작동하지 않습니다. 여기

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); 

이 해시 태그입니다 문자열의 첫 번째 문자를 생략합니다.

관련 문제