0

現在、私はこのような画像を持っています(CKEditorによって作成されました):

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

この画像の周りに div を追加し、テキストを alt タグからスパンに抽出したいと考えています。

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

ここまで神!しかし、img からスタイル属性を取得し、それを新しく作成された div の CSS に追加したいとも考えています。どうすればこれを達成できますか?

4

5 に答える 5

3

これを試して

$(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")));
     });
});
于 2011-06-15T16:03:04.103 に答える
1

これを使用できます:

$(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');
     });
});

基本的に、各 DIV に一意の ID を作成し、毎回スタイルを適用しています

于 2011-06-15T16:07:50.623 に答える
0
$('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>');
});
于 2011-06-15T16:52:18.577 に答える
0

$(this).wrap("<div class='imgtxt' />");この行を次のように置き換えます。

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

これは、画像のスタイル属性を取得し、新しい に追加しますdiv

于 2011-06-15T16:02:44.560 に答える
0
$(this).closest('div.imgtxt').attr('style', $(this).attr('style'));

closest()div作成したばかりのあなたをつかみます。コードを次のように変更することもお勧めします。

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

$(this)このようにして、呼び出されるたびに jQuery オブジェクトを検索/作成する必要がなくなります。

于 2011-06-15T16:02:41.960 に答える