我一直在试着自己解决这个问题,因为看起来应该很容易,但事实证明我有点白痴。。。
基本上,我试图将特定"a"标签的内容移动到其外部,然后将该"a"标记移动到包含图的末尾…
<figure class="myFigure">
<a href="#">
<img src="#">
</a>
<figcaption>Sample Caption</figcaption>
</figure>
更改为…
<figure class="myFigure">
<img src="#">
<figcaption>Sample Caption</figcaption>
<a href="#"></a>
</figure>
请注意,在一个页面上有多个以上内容的实例,有些有链接,有些没有。我不想影响那些没有链接的。
首先,我一直在尝试以下的变体,但这会在每个图形中创建每个图像的多个实例…
$('.myFigure').each(function() {
$('a',this).contents().insertBefore( 'figcaption' );
});
问候Ciarán
要获得预期结果,可以使用:
$('.myFigure').append(function() {
return $(this).children('a').contents().unwrap().end();
});
我承认这是一个比a.Wolff的漂亮实现更"过程化"的方法。然而,正如你似乎想绕过所有元素一样——收集它们,然后将它们重新插入到你指定的顺序中会感觉更容易:
$('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 ]);
});
Fiddle:https://jsfiddle.net/hrhw1rxt/4/
您可以尝试以下操作,我假设链接可能包含图像之外的其他元素。
$('figure > a').each(function() {
var
$this = $(this),
$parent = $(this).closest('.myFigure');
$this.children().insertBefore($this);
$this.appendTo($parent);
})
a {
border: 1px solid blue;
}
<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>