当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - problems with each()

问题描述:

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

Everything is working fine but 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).

分享给朋友:
您可能感兴趣的文章:
随机阅读: