sourcecode

URL에서 해시 제거

copyscript 2023. 2. 15. 22:08
반응형

URL에서 해시 제거

프로젝트 중 하나에서 페이지 번호를 에이잭스하고 있으며, 사용자가 현재 페이지를 북마크할 수 있도록 하고 싶기 때문에 해시를 통해 페이지 번호를 첨부합니다.

onclick="callPage(2); window.location.hash='p=2'; return false;"

그리고 그것은 그 위에 있다hyperlink정상적으로 동작하며, 페이지 번호가 1일 때를 제외하고, 나는 모든 것을 하고 싶지 않다.URL되려고/products#p=1, 나는 단지 그것이 되길 바란다./products

저는 다음과 같은 변형을 시도했습니다.

  1. window.location.hash=''동작하지만 URL은 다음과 같습니다./products#그리고 나는 거기 있는 해시를 잘 모른다.
  2. window.location을 사용하지 않습니다.해시는 전혀 없지만 사용자가 페이지 3에서 페이지 1로 돌아왔을 때, 그는 페이지 1에 있지만 url은 아직 남아 있습니다./products#p=3해시를 건드리는 게 아니니까
  3. 이에 대한 구글 검색으로 몇 분(약 15)의 바보 같은 포럼에 접속할 수 있었습니다만, 답변은 스레드 작성자가 href에 해시가 있기 때문에 페이지가 점프하는 것을 시사하고 있었습니다.<a href="#">그리고 그는 그것을 사용해야 한다.javascript:void(0)대신.(그들은 아약스에 대해 들어본 적이 없는가?)

그래서 결국 이 스레드를 만들기로 했습니다.여기서 비슷한 스레드를 몇 개 찾았습니다만, 모든 답은 제 두 번째 포인트와 매우 비슷합니다.

그래서 나의 큰 질문은 여전히 의문으로 남아 있다.URL에서 해시를 쫓아내는 방법, 그리고 우주에서 해시를 쫓아내는 방법.(첫 페이지만!)

history.pushState("", document.title, window.location.pathname);

갱신된 답변:

이를 실현하기 위한 최선의 방법은 아래의 Homero Barbosa의 답변따르는 것입니다.

history.pushState("", document.title, window.location.pathname);

... 또는 검색 매개 변수를 유지하려는 경우:

history.pushState("", document.title, window.location.pathname + window.location.search);

원래 답변, 사용하지 마십시오. 잘못된 재미:

var loc = window.location.href,
    index = loc.indexOf('#');

if (index > 0) {
  window.location = loc.substring(0, index);
}

...근데 도착하자마자 조금 무례해 보이는 페이지가 새로워졌네요.웃으며 참는 것이 최선의 선택인 것 같다.

완벽하게 작동

$(window).on('hashchange', function(e){
  window.history.pushState("", document.title, window.location.pathname);  
 // do something...
});
var urlWithoutHash = document.location.href.replace(location.hash , "" );
function removeHash () { 
    var scrollV, scrollH, loc = window.location;
    if ("pushState" in history)
        history.pushState("", document.title, loc.pathname + loc.search);
    else {
        // Prevent scrolling by storing the page's current scroll offset
        scrollV = document.body.scrollTop;
        scrollH = document.body.scrollLeft;

        loc.hash = "";

        // Restore the scroll offset, should be flicker free
        document.body.scrollTop = scrollV;
        document.body.scrollLeft = scrollH;
    }
}

언급URL : https://stackoverflow.com/questions/4508574/remove-hash-from-url

반응형