当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

This doesn't seem to be working for me. I want to perform these actions only on images with a title attribute set. It seems my problem is when I use $(this), it is referring to the title attribute? Thanks in advance.

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

网友答案:

It seems you got mixed-up with the if and the each(). You should apply your each to your selector directly. If no image have a title attribute then it won't do anything, else it will apply your function to each element.

(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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: