检查图像是否具有title属性,然后应用于图像选择器

时间:2013-02-05 19:11:58

标签: javascript jquery

这似乎对我不起作用。我想只对设置了title属性的图像执行这些操作。看来我的问题是当我使用$(this)时,它指的是title属性?提前谢谢。

(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);

1 个答案:

答案 0 :(得分:7)

您似乎混淆了ifeach()。您应该直接将每个应用于您的选择器。如果没有图像具有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);
相关问题