我有一个图像列表,我想在每个段落后插入一张图像。有时我的图像比段落少,有时更多。如何循环遍历 img 元素以将它们插入到段落之后,如果图像太多,请将它们保留在原来的位置?
$( ".img" ).insertAfter( "p" );
如果没有内容,结构将如下所示:
之前:
<div id="wrap">
<h2></h2>
<p></p>
<h2></h2>
<p></p>
<h2></h2>
<p></p>
</div>
<img class="img" />
<img class="img" />
<img class="img" />
<img class="img" />
<img class="img" />
<img class="img" />
<img class="img" />
<img class="img" />
结果:
<div id="wrap">
<h2></h2>
<p></p>
<img class="img" />
<h2></h2>
<p></p>
<img class="img" />
<h2></h2>
<p></p>
<img class="img" />
</div>
<img class="img" />
<img class="img" />
<img class="img" />
<img class="img" />
<img class="img" />
最佳答案
您可以使用.after()
方法:
var $img = $('.img');
$('#wrap p').after(function(i) { return $img.eq(i); });
关于javascript - 在段落列表后插入图像列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26645793/