为什么2张图片前置?

时间:2013-10-23 09:33:42

标签: jquery prepend

我尝试将图像添加到img-wrapper div并将其包装在标题后锚点的href中。也许这令人困惑。下面是代码:

     $(".post").each(function() {
    if($(this).find(".post-excerpt > p:first-child").has("img").length){

        if($(this).find(".post-title").has("a").length){

            $(this).find(".img-wrapper").prepend("<a href='"+$(this).find(".post-title a").attr("href")+"'></a>");

            $(this).find(".post-excerpt > p:first-child").has("img").find("img").prependTo($(this).find(".img-wrapper a"));

        }else{

            $(this).find(".post-excerpt > p:first-child").has("img").find("img").prependTo($(this).find(".img-wrapper"));
        }
    }
});

一切正常,但是锚和div正在2个地方添加,正确的地方(.img-wrapper内部,还有.post-title a。我无法理解为什么要添加它到post-title a。这是生成的html:

<article class="post">

    <div class="img-wrapper"><a href="/test-image-post/#top"><img alt="" src="/content/images/2013/Oct/img.jpg"></a>

        <header class="post-header">

            <h2 class="post-title"><a href="/test-image-post/#top"><img alt="" src="/content/images/2013/Oct/img.jpg">Post Title</a></h2>

        </header>

        <section class="post-excerpt">

        </section>

    </div>

</article>

同样,我试图仅将图像添加到img-wrapper div。感谢。

1 个答案:

答案 0 :(得分:1)

我已尝试在我的本地系统上复制您的代码,并发现图片因为:

而来了两次
".img-wrapper a", instead you have to use it as ".img-wrapper > a:first-child" after prepending anchor.

在这里小提琴:http://jsfiddle.net/BvGXs/

图片未因路径而加载,但前提是正确的。