假设我有一个看起来像这样的锚点
<div class="res">
<a href="~/Resumes/Resumes1271354404687.docx">
~/Resumes/Resumes1271354404687.docx
</a>
</div>
注意:该锚点不会有任何id或class属性...
我希望在jQuery onclick
中获取该锚点的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"));
});
});
使用纯JavaScript就可以很简单地完成此操作,因此您不需要jQuery。以下是两个选项:
Method 1 - Retrieve the exact value of the href
attribute:
Select the element and then use the .getAttribute()
method.
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>
根据您的标题,您想要在点击时获取href
值。只需选择一个元素,添加单击事件监听器,然后使用上述任一方法返回href
值即可。
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>
更新的代码
$('a','div.res').click(function(){
var currentAnchor = $(this);
alert(currentAnchor.text());
alert(currentAnchor.attr('href'));
});
$('a','div.res')
做了什么。 - Sarfraz使用Sarfraz上面的示例。
<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);
});
});
link
类应该是用于他想要获取信息的特定链接。 - Sarfraz<div class='link' />
,该怎么办? - rahul