jquery click event reference with [this]
I have some hyperlinks and when user clicks on any of them I want to direct the user to that particular link. I am accessing the href attribute with jquery. Below is the code.
<a href="http://www.google.com" class="class-name">link1</a>
<a href="http://www.facebook.com" class="class-name">link1</a>
<a href="http://www.yahoo.com" class="class-name">link1</a>
Now I want to access the URL with jQuery I am using the below code:
$(document).ready(function(开发者_Python百科) {
$('.class-name').click(function(){
var linkHref=$("this.class-name").attr('href');
alert(linkHref);
$('.redirect').attr('href',linkHref);
});
But I am getting "undefined" in the alert.
All your help is highly appreciated.
Change your code like this
$(document).ready(function() {
$('.class-name').click(function(){
var linkHref=$(this).attr('href');
alert(linkHref);
});
this is the object < a > that you selected with the click method. Thus you do not need to let jQuery search for the object based on class or id as previously. Hope this clarifies.
var linkHref=$(this).attr('href');
Your selector is wrong.
this
is a special identifier that gets the context that your function is called in. It doesn't make sense to write "this"
; the jQuery
function has no way of knowing what your this
is.
You probably want $(this)
.
You can also write $(this).find('.redirectLink')
, but that isn't the code you're looking for.
In jQuery this refers to the current object in scope. In the case of a click event this refers to the hyperlink being clicked. But do not enclose it in quotes.
$(document).ready(function() {
$('.class-name').click(function(){
var linkHref=$(this).attr('href');
alert(linkHref);
$('.redirect').attr('href',linkHref);
});
});
you could shorten this to:
$(document).ready(function() {
$('.class-name').click(function(){
$('.redirect').attr('href',$(this).attr('href'));
});
});
精彩评论