javascript
  • get
  • url-parameters
  • 2014-01-29 3 views 0 likes 
    0

    다음과 같이 HTML

    <html> 
    <title>Example</title> 
    <head> 
    </head> 
    <body> 
         <h2>Profile Photo</h2> 
        <div id="photo-container">Photo will load here</div> 
        <script type='text/javascript' src='http://example.com/js/coverphoto.js?name=johndoe'></script> 
    </body> 
    </html> 
    

    내 HTML 블록을 스크립트 소스 파일에서 자바 스크립트 URL 매개 변수를 얻고 나는 test.html이 파일을 저장했습니다. JavaScript 소스에서 이름은 동적입니다. coverphoto.js에서 이름을 수집하고 싶습니다. coverphoto.js에서 시도한 것처럼,

    window.location.href.slice(window.location.href.indexOf('?') + 1).split('&') 
    

    그러나 html 파일 이름 (test.html) 만 표시됩니다. coverphoto.js의 http://example.com/js/coverphoto.js?name=johndoe에서 이름 키를 검색하려면 어떻게해야합니까?

    답변

    2

    현재 JavaScript 파일의 URL을 얻으려면 현재 페이지에있는 마지막 <script> 요소가 사용될 수 있습니다.

    var scripts = document.getElementsByTagName('script'); 
    var script = scripts[scripts.length - 1]; 
    var scriptURL = script.src; 
    

    그것이 JS 파일에서 직접 실행하는 경우이 코드는뿐만 아니라 문서 준비 콜백 또는 비동기라고 아무것도 내부 즉, 작동 있습니다. 그런 다음 "get querystring parameter" JS을 사용할 수 있습니다 (단, 거기에있는 location.search 참조를 대체하여 인수를 추출 할 수 있습니다).

    나는 data-name 인수에 값을 넣으라고 제안합니다. 그런 식으로 간단히 예를 들어. script.getAttribute('data-name') 값을 가져옵니다.

    관련 문제