I'm trying to get href value using jQuery:
<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>
But it doesn't work. Why?
You need
var href = $(this).attr('href');
Inside a jQuery click handler, the this
object refers to the element clicked, whereas in your case you're always getting the href for the first <a>
on the page. This, incidentally, is why your example works but your real code doesn't
You can get current href value by this code:
$(this).attr("href");
To get href value by ID
$("#mylink").attr("href");
It's worth mentioning that
$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always
它有效...在 IE8 中测试(如果您正在测试计算机上的文件,请不要忘记允许 javascript 运行)和 chrome。
如果页面有一个<a>
可以,但是,很多<a>
必须使用var href = $(this).attr('href');
**Replacing href attribut value to other**
<div class="cpt">
<a href="/ref/ref/testone.html">testoneLink</a>
</div>
<div class="test" >
<a href="/ref/ref/testtwo.html">testtwoLInk</a>
</div>
<!--Remove first default Link from href attribut -->
<script>
Remove first default Link from href attribut
$(".cpt a").removeAttr("href");
Add Link to same href attribut
var testurl= $(".test").find("a").attr("href");
$(".test a").attr('href', testurl);
</script>
If your html link is like this:
<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>
Then you can access the href in jquery as given below (there is no need to use "a" in href for this)
$(".linkClass").on("click",accesshref);
function accesshref()
{
var url = $(".linkClass").attr("href");
//OR
var url = $(this).attr("href");
}
<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>
$(".linkClass").click(function() {
alert($(this).attr("href"));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.