Insert an image between paragraphs with jQuery
I have a div with several paragraphs and another div with a set of images. Like so:
<div id="interview">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
<p>Ased do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<p>Three ipsum dolor sit amet, consectetur adipisicing elit</p>
<p>Four do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<p>Five开发者_开发知识库 ipsum dolor sit amet, consectetur adipisicing elit</p>
<p>Six do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div id="images">
<img src="http://placehold.it/100x100/ff0000" class="imgThumb" id="img1" />
<img src="http://placehold.it/100x100/39719c" class="imgThumb" id="img2" />
<img src="http://placehold.it/100x100/eeeeee" class="imgThumb" id="img3" />
<img src="http://placehold.it/100x100/000000" class="imgThumb" id="img4" />
</div>
What I'd like to do is use jQuery to take each one of the images and insert it after every second paragraph. I'm just not well versed enough in jQuery to traverse and loop through the divs to accomplish what I need. :(
By "every second paragraph," I assume you mean the odd-numbered paragraphs (zero-indexed), e.g., 1, 3, 5, ... . I assume this because you have 4 images and 6 paragraphs. If I assume wrong, then you'd change the :odd
selector to something like :nth-child(3n+1)
, which would select paragraphs 1, 4, 7, ...
$(function ()
{
var $images = $('#images > img');
$('#interview > p:odd').each(function (i)
{
$(this).after($images.get(i));
});
});
API docs:
:odd
selector.after()
Oh also
check out the demo →
精彩评论