开发者

jQuery insertBefore, insertAfter problem

I want to make my images as links with help of jQuery:

 $("img:gt(0)").each(function () {
            var curr = $(this);
            if (curr.width() >= 500) {
                var m = 500 / curr.width();
                curr.height(curr.height() * m);
                curr.width(curr.width() * m);
            }
            $("<a href='" + curr.attr("src") + "'>").insertBefore(curr);
            $("</a>").insertAfter(curr);
        });

But I'm getting:

<a href="/Images/7827-1280x800.jpg"></a>
<img height="800" width="1280" src="/Images/7827-1280x800.jpg" alt=开发者_运维技巧"" style="height: 312.5px; width: 500px;">

Instead of:

<a href="/Images/7827-1280x800.jpg">
<img height="800" width="1280" src="/Images/7827-1280x800.jpg" alt="" style="height: 312.5px; width: 500px;">
</a>


You don't have to do like this. You can use wrap to do this.

Something like

curr.wrap("<a href='" + curr.attr("src") + "' />");


You could use the wrap() method provided by jQuery

$("img:gt(0)").each(function () {
    var curr = $(this);
    if (curr.width() >= 500) {
        var m = 500 / curr.width();
        curr.height(curr.height() * m);
        curr.width(curr.width() * m);
    }
    curr.wrap($('<a href="' + curr.attr("src") + '">'));
});


It's because $("<a href='" + curr.attr("src") + "'>") will create a common html element. I think, jQuery will ignore missing closing tag and create this html: <a href="/Images/7827-1280x800.jpg"></a> and $("</a>") will be ignored at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜