0

これは私にはうまくいかないようです。これらのアクションは、タイトル属性が設定された画像に対してのみ実行したいと考えています。私の問題は、使用するとき$(this)のようですが、タイトル属性を参照していますか? 前もって感謝します。

(function($) {
  $(function() {
    /* Run this only if images have a title attribute */
    if ($('.node-page img[title], .node-news img[title]')) {
      $(this).each(function() {
        var image = $(this);
        var caption = image.attr('title');
        var imagealign = image.css('float');

        image.after('<span class="caption">' + caption + '</span>');
        image.next('span.caption').andSelf().wrapAll('<div>');
        image.parent('div').addClass('caption-wrapper').css({'width': imagewidth, 'height': 'auto', 'float': imagealign});
      });
    }
  });
})(jQuery);
4

1 に答える 1

7

と を混同したようifですeach()。each をセレクターに直接適用する必要があります。画像にtitle属性がない場合は何もしません。それ以外の場合は、関数を各要素に適用します。

(function($) {
  $(function() {
    /* Run this only on images that have a title attribute */
    $('.node-page img[title], .node-news img[title]').each(function() {
        var image = $(this);
        var caption = image.attr('title');
        var imagealign = image.css('float');

        image.after('<span class="caption">' + caption + '</span>');
        image.next('span.caption').andSelf().wrapAll('<div>');
        image.parent('div').addClass('caption-wrapper').css({'width': imagewidth, 'height': 'auto', 'float': imagealign});
    });
  });
})(jQuery);
于 2013-02-05T19:13:22.617 に答える