开发者

Referring to an object's ID in a jQuery append statement

开发者 https://www.devze.com 2022-12-25 10:45 出处:网络
I have this element: <div class=\"isthisyou\" id=\"unique_identifier\"></div> I want to use jQuery to insert a link into the div:

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:

  1. The selector for class foo should be ".foo" rather than "foo"
  2. The ID is variable for each element; you cannot use the same value in the append() call
  3. 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>');
0

精彩评论

暂无评论...
验证码 换一张
取 消