Currently I have an image like this (created by CKEditor):

<img src="foo.jpg" style="float: left; margin-left: 20px;" alt="Image text">

I want to add a div around this image and extract the text from the alt-tag into a span.

$(document).ready(function () {
    $("#foo img").each(function() {
        $(this).wrap("<div class='imgtxt' />");
        $(this).after($("<span />").text($(this).attr("alt")));
     });
});

So far so god! But I also want to get the style attributes from the img and add that to the CSS of the newly created div. How can I achieve this?

有帮助吗?

解决方案

Try this

$(document).ready(function () {
    $("#foo img").each(function() {
        $(this).wrap("<div class='imgtxt' />");
        $('.imgtxt').attr('style', $(this).attr('style'));
        $(this).after($("<span />").text($(this).attr("alt")));
     });
});

其他提示

You can use this:

$(document).ready(function () {
    $("#foo img").each(function(index) {
        $(this).wrap("<div id='newdiv" + index + "'" class='imgtxt' />");
        $(this).after($("<span />").text($(this).attr("alt")));
        $("#newdiv" + index).attr('style', $(this).attr('style');
     });
});

You're basically creating a unique ID for each DIV and then applying the style each time

$(this).closest('div.imgtxt').attr('style', $(this).attr('style'));

closest() will grap your div you just created. I'd also recommend changing the code to something like this:

$("#foo img").each(function() {
    var $this = $(this);
    $this.wrap("<div class='imgtxt' />");
    $this.after($("<span />").text($this.attr("alt")));
    // etc.
 });

This way you are not looking up/making a jQuery object every time $(this) is called!

Replace this line $(this).wrap("<div class='imgtxt' />"); with:

$(this).wrap("<div class='imgtxt' style=\"" + $(this).attr("style") + "\" />");

This takes the style attribute of the image and adds it to the new div.

$('img').each(function() {
    var alt   = $(this).attr('alt'),
        style = $(this).attr('style');
    $(this).after("<span>" + alt + "</span>")
           .next('span')
           .andSelf()
           .wrapAll('<div class="imgtxt" style="'+style+'"></div>');
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top