[javascript] jQuery를 사용하여 href 값을 얻는 방법?

jQuery를 사용하여 href 값을 얻으려고합니다.

<html>
    <head>
        <title>Jquery Test</title>
         <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $("a").click(function(event) {
                alert("As you can see, the link no longer took you to jquery.com");
                var href = $('a').attr('href');
                alert(href);
                event.preventDefault();
            });
        });
        </script>
    </head>
    <body>
        <a href="http://jquery.com/">jQuery</a>
    </body>
</html>

그러나 작동하지 않습니다. 왜?



답변

당신은 필요

var href = $(this).attr('href');

jQuery 클릭 핸들러 내에서 this객체는 클릭 한 요소를 참조하지만 귀하의 경우 항상 <a>페이지 의 첫 번째 에 대한 href를 얻습니다 . 우연히도 예제가 작동하지만 실제 코드는 그렇지 않습니다.


답변

이 코드로 현재 href 값을 얻을 수 있습니다.

$(this).attr("href");

ID로 href 값을 얻으려면

$("#mylink").attr("href");


답변

그것은 작동합니다 … IE8 (컴퓨터에서 파일을 테스트하는 경우 자바 스크립트를 실행하는 것을 잊지 마십시오)과 크롬에서 테스트되었습니다.


답변

페이지에 <a>작동 하는 페이지가있는 경우에는 많은 페이지 <a>를 사용해야합니다.var href = $(this).attr('href');


답변

언급 할 가치가 있습니다.

$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always


답변