假设我有4个img标签,它们具有相同的类,并且每个标签都有不同的URL。我可以使用以下代码检索每个网址:
$('.userPicture img').each(function(){
var getImageLink = $(this).attr('src');
console.log(getImageLink)
});
CONSOLE.LOG:
http://link1.com
http://link2.com
http://link3.com
http://link4.com
问题是如何每班只附加一次链接?
$.each(getImageLink, function(i) {
$('.aboutInfo').eq(i).append('<p><a href="'+getImageLink+'"></a></p>');
});
我能得到的最好结果是:
.aboutInfo
http://link1.com
http://link2.com
http://link3.com
http://link4.com
.aboutInfo
http://link1.com
http://link2.com
http://link3.com
http://link4.com
我需要的是:
.aboutInfo
http://link1.com
.aboutInfo
http://link2.com
等...
我无法通过myselft弄明白:(
答案 0 :(得分:1)
这应该有效
$('.userPicture img').each(function(i, el){
var getImageLink = $(el).attr('src');
$('.aboutInfo').eq(i).append('<p><a href="'+getImageLink+'"></a></p>');
});
关键是在.each循环中进行追加...这样getImageLink将是正确的值(它在范围内)并且它将附加到每个链接一次。
更新:要回答评论中提出的问题,您不需要在链接中包含文本以使其有效。 CSS可能就是这样:
.aboutInfo {
background: url(http://server.com/images/20x100-image.png) center left no-repeat;
height: 20px;
width: 100px;
display: block;
}
无论哪种方式,链接没有文字的原因并不是OP问题的重点,但希望这种解释能帮助任何好奇的人。