展开<img/>代码并移动<a> tag to another <img/></a>

时间:2014-08-13 15:49:56

标签: jquery

我有一个带链接的图像。这是我的标记:

<figure>
   <a href="index.php/home.html">
      <img src="300x380.png" width="300" height="380" alt="">
   </a>
</figure>

现在,我需要另一个位置的链接,但是如何?

<a href="index.php/home.html">
    <img src="otherimg.png">
</a>

<figure>
       <img src="300x380.png" width="300" height="380" alt="">
</figure>

这是我的jQuery,但只是解包部分。

$('figure a img').unwrap('<a>');

3 个答案:

答案 0 :(得分:0)

$('figure').each(function () {
    var myFigure = $(this);
    var myAnchor = $(myFigure).find('a');
    var myImage  = $(myAnchor).find('img');
    var newImage = '<img src="http://placekitten.com/g/200/200" alt="" />';

    $(myFigure).append(myImage).before(myAnchor);
    $(myAnchor).html(newImage);
});

http://jsfiddle.net/isherwood/db63f0zh

可能不需要each()功能,但它将涵盖更多场景。

答案 1 :(得分:0)

你可以试试这个:

var aTag = ($('figure').children('a')).clone();
var newTag = $(aTag).children('img').attr('src','otherimg.png');
$('figure').parent().append(newTag);
$('figure a img').unwrap('<a>');

工作Fiddle.

答案 2 :(得分:0)

无需解包 -

var originalImg = $('figure > a').html();
$('figure > a').prependTo('body').html('<img src="http://placehold.it/200x280">'); // this moves the a tag and then adds the other image info to it
$(originalImg).appendTo('figure');

示例 - http://jsfiddle.net/ysnwaxLm/1/

相关问题