JavaScript/jQuery로 현재 URL 가져오기
이 게시물에서는 JavaScript 및 jQuery에서 페이지의 현재 URL을 가져오는 방법에 대해 설명합니다.
1. JavaScript 사용하기
그만큼 Location JavaScript의 객체는 문서의 현재 URL에 대한 정보를 포함합니다. 다음을 사용하여 액세스할 수 있습니다. Window
상호 작용. 그래서, 당신은 사용할 수 있습니다 Window.location 현재 문서의 Location 개체를 가져옵니다. 그 다음에 href
재산 location.href
전체 URL이 포함된 문자열을 가져오는 데 사용할 수 있습니다.
그만큼 Location
객체는 URL의 프로토콜, 호스트, 도메인, 포트 번호, 경로 이름 등을 가져오기 위한 몇 가지 다른 속성을 제공합니다. 예를 들어,
1 2 3 4 5 6 7 8 9 |
window.location.href // https://example.com:8080/get?post=123#selector window.location.protocol // https: window.location.host // example.com:8080 window.location.hostname // example.com window.location.port // 8080 window.location.pathname // /가져 오기 window.location.search // ?post=123 window.location.hash // #선택자 window.location.origin // https://example.com:8080 |
또는 액세스할 수 있습니다. Location
반대 Document.location 재산 Document
상호 작용. 당신은 또한 사용할 수 있습니다 document.URL
또는 document.documentURI
속성을 사용하여 현재 문서의 URL을 가져옵니다.
1 2 3 4 5 6 7 8 9 10 11 12 |
document.location.href // https://example.com:8080/get?post=123#selector document.location.protocol // https: document.location.host // example.com:8080 document.location.hostname // example.com document.location.port // 8080 document.location.pathname // /가져 오기 document.location.search // ?post=123 document.location.hash // #선택자 document.location.origin // https://example.com:8080 document.URL // https://example.com:8080/get?post=123#selector document.documentURI // https://example.com:8080/get?post=123#selector |
2. jQuery 사용하기
jQuery를 사용하면 다음을 사용할 수 있습니다. .prop()
또는 .attr()
아래와 같이 위치 개체의 속성을 가져오는 메서드:
1 2 3 4 5 6 7 8 9 |
$(location).attr('href'); // https://example.com:8080/get?post=123#selector $(location).attr('protocol'); // https: $(location).attr('host'); // example.com:8080 $(location).attr('hostname'); // example.com $(location).attr('port'); // 8080 $(location).attr('pathname'); // /가져 오기 $(location).attr('search'); // ?post=123 $(location).attr('hash'); // #선택자 $(location).attr('origin'); // https://example.com:8080 |
JavaScript 및 jQuery에서 현재 URL을 가져오는 것이 전부입니다.
또한 참조: