Been trying to figure this out for myself as it seems like it should be easy enough however it turns out I'm a bit of an idiot...
Basically I'm trying to move the contents of a specific 'a' tag to just outside itself and then move that 'a' tag to the end of the containing figure...
<figure class="myFigure">
<a href="#">
<img src="#">
</a>
<figcaption>Sample Caption</figcaption>
</figure>
Change to...
<figure class="myFigure">
<img src="#">
<figcaption>Sample Caption</figcaption>
<a href="#"></a>
</figure>
Note there is multiple instances of the above on a page, some with links and some without. I dont wish to effect the ones without a link.
To start off I've been trying variations of the following however this create multiples instances of each image within each figure...
$('.myFigure').each(function() {
$('a',this).contents().insertBefore( 'figcaption' );
});
Regards Ciarán
答案 0 :(得分:1)
要获得预期结果,您可以使用:
$('.myFigure').append(function() {
return $(this).children('a').contents().unwrap().end();
});
答案 1 :(得分:1)
我承认这是一个更为程序化的程序。方法比A.沃尔夫的好实施。然而,因为看起来你想要围绕所有元素进行夹具 - 收集它们然后将它们重新插入到你指定的顺序中会感觉更容易一些:
$('figure').each(function(){
var $that = $(this);
var getimg = $that.find( 'img' );
var getLink = $that.find( 'a' );
var getFig = $that.find( 'figcaption' );
$that.empty().append([ getimg, getFig, getLink ]);
});
答案 2 :(得分:0)
您可以尝试下面的内容,我认为该链接可能包含除图像之外的其他元素。
$('figure > a').each(function() {
var
$this = $(this),
$parent = $(this).closest('.myFigure');
$this.children().insertBefore($this);
$this.appendTo($parent);
})
&#13;
a {
border: 1px solid blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<figure class="myFigure">
<a href="#">
<img src="#">
</a>
<figcaption>Sample Caption</figcaption>
</figure>
&#13;