0

我有一个 DIV 列表,它们都包含一段文本、一个图像和一个锚点。

使用 Javascript/jQuery,是否可以获取锚点的 href,并使用该链接将图像包装在锚点标签中?

我知道这是一个奇怪的要求,我做了一个小提琴......

http://jsfiddle.net/fFgwb/


会有多个 div,所以我不能有相同的 id

4

6 回答 6

1

这是一种方法

var src = $("#imgid").attr("src"); //take out the src
$("#imgid").wrap($('<a href="'+src+'" />'); //wrap around it with the anchor

你的用法,可能是这样的

$("img", $("#divid")).each(function() {
    var src = $(this).attr("src"); //take out the src
    $(this).wrap($('<a href="'+src+'" />')); //wrap around it with the anchor

});

这是一个在你的小提琴上实现的演示。

于 2012-04-18T19:09:35.480 回答
0

尝试:

$('img').each(function(){
    $(this).wrap('<a href="'+$(this).attr('src')+'"/>');
});

只是缩小那个img选择器,也许有一个类。

于 2012-04-18T19:13:01.160 回答
0

如果我正确地得到了你想要的东西,你可以这样做:

$('a').attr('href', function() {
    return $(this).find('img').attr('src');
});​

正如你在这里看到的。

于 2012-04-18T19:13:21.770 回答
0

您应该将 .divs 之类的类添加到 div 和其他类以锚链接:

$(document).ready(function(){

$(".divs").each(function(){

    $(this).find("a").hasClass("anchor").attr("href", $(this).find("a").hasClass("continue").attr('href'))

});

});
于 2012-04-18T19:27:39.423 回答
0

使用 jQuery:

$('.card-prod').each(function () {
    var that = $(this),
        imgA = that.find('a img').parent(),
        newHref = that.find('a').not(imgA).attr('href');
    imgA.attr('href', newHref);
});
于 2012-04-18T19:15:21.427 回答
0

好吧,让我们总结一下:

  • 你会有几张卡
  • 每张卡片包含两个锚点
  • 第一个锚点应该获得与第二个锚点相同的 href 值

翻译成 jQuery:

$(".card-prod").each(function(){
    var anchors = $(this).find("a");
    anchors.eq(0).prop("href", anchors.eq(1).prop("href"));
});
于 2012-04-18T19:30:40.947 回答