我正在学习js和jquery并且一直试图解决这个问题,当我试图在页面上遍历ul并在我的html中将dom元素专门用于图像上升两个级别时。这是html的样子:
<ul class="feedEkList">
<li class="slick-slide">
<div class="featured-title">
<div class="post-title">
<a href="some url" target="_blank">some text</a>
</div>
<div class="post-excerpt">
<img src="imageurl.jpg" class="wp-post-image">
<p>Post Description.</p>
</div>
</div>
</li>
</ul>
我的ul中有10个li项目,但为了便于阅读,我只包括一个,所以你可以看到我的html结构。
我的javascript似乎是在每个精选标题div之前添加所有图像,这些图片为我提供了成堆的图片而不是与该li相关联的图片。
$(function() {
$('.wp-post-image').insertBefore($('.featured-title'));
});
然后我尝试使用每个,但它似乎没有做任何事情。
$(function() {
$('.feedEkList > li > .featured-title > .post-excerpt > .wp-post-image').each(function() {
$('.wp-post-image').insertBefore($('.featured-title'));
});
});
我想也许我需要在代码中使用“this”但我不熟悉javascript并且不确定如何正确使用“this”与插入之前,或者如果“this”甚至是最好的选择。
$('this.wp-post-image').insertBefore($('this.featured-title'));
任何人都可以帮我弄清楚我做错了什么吗?这让我疯了!
答案 0 :(得分:0)
.slick-slide
。.prepend
.slick-slide
.featured-title
之前插入,请参阅评论。
$('.wp-post-image').each(function() {
var $this = $(this),
parentLi = $this.parents('.slick-slide').first();
$this.prependTo(parentLi);
//$this.insertBefore(parentLi.find('.featured-title'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="feedEkList">
<li class="slick-slide">
<div class="featured-title">
<div class="post-title">
<a href="some url" target="_blank">some text</a>
</div>
<div class="post-excerpt">
<img src="http://i.stack.imgur.com/FgiPG.jpg" class="wp-post-image" />
<p>Post Description.</p>
</div>
</div>
</li>
<li class="slick-slide">
<div class="featured-title">
<div class="post-title">
<a href="some url" target="_blank">some text</a>
</div>
<div class="post-excerpt">
<img src="http://i.stack.imgur.com/FgiPG.jpg" class="wp-post-image" />
<p>Post Description.</p>
</div>
</div>
</li>
<li class="slick-slide">
<div class="featured-title">
<div class="post-title">
<a href="some url" target="_blank">removed the "wp-post-image" class to show how it was look before</a>
</div>
<div class="post-excerpt">
<img src="http://i.stack.imgur.com/FgiPG.jpg" />
<p>Post Description.</p>
</div>
</div>
</li>
</ul>