如何获得锚文本/href 点击使用 jQuery?

我有一个像这样的锚

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

注意: 这个锚不会有任何 id 或类..。

I want to get either href/text in the jQuery onclick of that anchor.

354796 次浏览

注意: 将类 info_link应用到您想要获得信息的任何链接。

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

For href:

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

文字:

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

.

基于问题编辑的更新

你现在可以像这样得到它们:

参考:

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

文字:

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

更新代码

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

Edited to reflect update to question

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

没有 jQuery:

如果使用纯 JavaScript 来实现这一点非常简单,那么你就不能使用 need jQuery:

  • 方法1-检索 href属性的确切值:

    Select the element and then use the .getAttribute() method.

    这个方法返回完整的 URL,而不是检索 href属性的确切值。

    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>

另一种选择

Using the example from Sarfraz above.

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

参考:

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