开发者

problems with each()

开发者 https://www.devze.com 2023-02-24 14:31 出处:网络
I am trying to insert a link at the end of each .item. Everything is working fine bu开发者_StackOverflow社区t I get 7 printouts of the link after each element.

I am trying to insert a link at the end of each .item.

Everything is working fine bu开发者_StackOverflow社区t I get 7 printouts of the link after each element.

How can I get just the relevant link to print after each of it's .item?

Thank you so much!

$('#content .item img').each(function(i) {
    var altText = $(this).attr("alt");
    $('<br /><a href="' + altText + '">visit website</a>').insertAfter('.imagefield');
});


Change your selector to only find #content .item, not the images within. Presumably you're iterating over any nested images within .item (which would appear to be 7)

Remember that each will find all matches for the selector. If you're intent is only to work with .item, then you need to be specific and only select .item (not nested elements).

With no HTML in front of me, I would recommend:

$('#content .item').each(function(i,e){
  $(e).append('<br /><a href="' + $('img',e).attr('alt')+ '">visit website</a>');
});


You're calling insertAfter('.imagefield') which will find all .imagefield elements and insert a link after them - for each image. Try insertAfter(this).

0

精彩评论

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