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

Check if image has title attribute, then apply to image selector

本文关键字:图像 然后 选择器 属性 应用于 标题 是否 检查      更新时间:2023-09-26

这似乎对我不起作用。我只想在设置了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);

您似乎混淆了ifeach()。您应该将您的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);
相关文章: