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

Vin*_*ent 0 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);
Run Code Online (Sandbox Code Playgroud)

koo*_*jah 7

看起来你if和这个混淆了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);
Run Code Online (Sandbox Code Playgroud)