I have this element:
<div class="isthisyou" id="unique_identifier"></div>
I want to use jQuery to insert a link into the div:
$('isthisyou').append('<a href="auth/create_account/'+this.id+'">Is this you?</a>');
Right now this.id
is returning und开发者_如何学Goefined
instead of unique_identifier
. What am I doing wrong?
Thanks!
There's always this
$this = $('.isthisyou');
$this.append('<a href="auth/create_account/'+$this.attr('id')+'">Is this you?</a>');
It fails for three reasons:
- The selector for class
foo
should be".foo"
rather than"foo"
- The ID is variable for each element; you cannot use the same value in the append() call
- In your code,
this
does not mean what you thing it means
Try this instead:
$('.isthisyou').each(function(){
$(this).append('<a href="auth/create_account/'+this.id+'">Is this you?</a>');
});
Both of the above answers have small problems. Use
$('.isthisyou').append('<a href="auth/create_account/'+$(this).attr('id')+'">Is this you?</a>');
For classes in selectors use it as ".classname" (the dot), and unfortunately you have to access the id through $(this).attr().
$('.isthisyou').append('<a href="auth/create_account/'+$(this).attr("id")+'">Is this you?</a>');
If $(this).attr("id") is still undefined than that means that $(this) isn't set inside the append and you're going to have to use the following:
$('.isthisyou').each(function(){
$(this).append('<a href="auth/create_account/'+$(this).attr("id")+'">Is this you?</a>');
});
Try using attr
instead:
$('isthisyou').append('<a href="auth/create_account/'+$(this).attr('id')+'">Is this you?</a>');
Or as shown from the comments, you can try:
$('isthisyou').append('<a href="auth/create_account/'+$('isthisyou').attr('id')+'">Is this you?</a>');
精彩评论