development

jQuery를 사용하여 클릭시 앵커 텍스트 / href를 얻는 방법은 무엇입니까?

big-blog 2020. 8. 3. 17:22
반응형

jQuery를 사용하여 클릭시 앵커 텍스트 / href를 얻는 방법은 무엇입니까?


이 모양의 앵커가 있다고 생각하십시오.

 <div class="res">
     <a href="~/Resumes/Resumes1271354404687.docx">
         ~/Resumes/Resumes1271354404687.docx
     </a>
 </div>

참고 : 앵커에 대한 ID 또는 클래스는 없습니다 ...

onclick해당 앵커 의 jQuery에서 href / text를 가져오고 싶습니다 .


참고 :info_link 정보를 얻으려는 링크에 클래스 적용하십시오 .

<a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
    ~/Resumes/Resumes1271354404687.docx
</a>

href :

$(function(){
  $('.info_link').click(function(){
    alert($(this).attr('href'));
    // or alert($(this).hash();
  });
});

텍스트 :

$(function(){
  $('.info_link').click(function(){
    alert($(this).text());
  });
});

.

질문 편집에 따른 업데이트

이제 다음과 같이 얻을 수 있습니다.

href :

$(function(){
  $('div.res a').click(function(){
    alert($(this).attr('href'));
    // or alert($(this).hash();
  });
});

텍스트 :

$(function(){
  $('div.res a').click(function(){
    alert($(this).text());
  });
});

질문에 대한 업데이트를 반영하도록 편집

$(document).ready(function() {
    $(".res a").click(function() {
        alert($(this).attr("href"));
    });
});

jQuery없이 :

순수한 JavaScript를 사용하여 간단하게 수행 할 때는 jQuery가 필요 하지 않습니다 . 두 가지 옵션이 있습니다.

  • 방법 1- href속성 의 정확한 값을 검색 합니다.

    요소를 선택한 다음 .getAttribute()방법 을 사용하십시오 .

    This method does not return the full URL, instead it retrieves the exact value of the href attribute.

    var anchor = document.querySelector('a'),
        url = anchor.getAttribute('href');
    
    alert(url);
    <a href="/relative/path.html"></a>


  • Method 2 - Retrieve the full URL path:

    Select the element and then simply access the href property.

    This method returns the full URL path.

    In this case: http://stacksnippets.net/relative/path.html.

    var anchor = document.querySelector('a'),
        url = anchor.href;
    
    alert(url);
    <a href="/relative/path.html"></a>


As your title implies, you want to get the href value on click. Simply select an element, add a click event listener and then return the href value using either of the aforementioned methods.

var anchor = document.querySelector('a'),
    button = document.getElementById('getURL'),
    url = anchor.href;

button.addEventListener('click', function (e) {
  alert(url);
});
<button id="getURL">Click me!</button>
<a href="/relative/path.html"></a>


Updated code

$('a','div.res').click(function(){
  var currentAnchor = $(this);
  alert(currentAnchor.text());
  alert(currentAnchor.attr('href'));
});

Alternative

Using the example from Sarfraz above.

<div class="res">
    <a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
        ~/Resumes/Resumes1271354404687.docx
    </a>
</div>

For href:

$(function(){
  $('.res').on('click', '.info_link', function(){
    alert($(this)[0].href);
  });
});

참고URL : https://stackoverflow.com/questions/2652372/how-to-get-anchor-text-href-on-click-using-jquery

반응형