javascript - jQuery Add Image Title Attribute from Alt - Stack Overflow

jQuery('img').each(function() {jQuery(this).attr('title', jQuery(this).attr('a

jQuery('img').each(function() {
    jQuery(this).attr('title', jQuery(this).attr('alt'));
})

How can I modify the code above so that it only applies the title attribute from alt if it doesn't already have a title attribute? In other words, if the image already has a non-empty title attribute, this code shouldn't execute.

jQuery('img').each(function() {
    jQuery(this).attr('title', jQuery(this).attr('alt'));
})

How can I modify the code above so that it only applies the title attribute from alt if it doesn't already have a title attribute? In other words, if the image already has a non-empty title attribute, this code shouldn't execute.

Share Improve this question asked Apr 21, 2015 at 6:55 Rick HelstonRick Helston 7634 gold badges12 silver badges21 bronze badges 1
  • Use this Selector: jQuery('img:not([title!=""][title])').each(function() { jQuery(this).attr('title', jQuery(this).attr('alt')); }) – Kailash Yadav Commented Apr 21, 2015 at 7:16
Add a ment  | 

7 Answers 7

Reset to default 4
jQuery('img').each(function () {
    $this = $(this);
    if (!$this.attr('title') && $this.attr('alt')) {
        $this.attr('title', $this.attr('alt'));
    }
})

By using a condition to check if the 'alt' attribute exists:

if (jQuery(this).attr('alt') != undefined) {
    jQuery(this).attr('title', jQuery(this).attr('alt'));
}

JS

jQuery('img').each(function() {
    var jq=jquery(this)
    var title= jq.attr('title');
     if(title == undefined)
       jq.attr('title', jq.attr('alt'));
});

You can also use the setter version of .attr() like

jQuery('img').attr('title', function () {
    if (!this.title) {
        return this.alt
    }
})

Demo: Fiddle

jQuery('img:not([title!=""][title])').each(function() {
    jQuery(this).attr('title', jQuery(this).attr('alt'));
})

You can use this selector which will take care of all img tags with or without title attribute exists and if exists, it should be empty.

This should do the trick.

jQuery('img').each(function () {
    var $el = jQuery(this),
        title = $el.attr('title'),
        alt = $el.attr('alt');
    if (title === undefined || title == '' || alt === undefined || alt == '')
        return;

    $el.attr('title', alt);
});

The code above will skip all images that have an empty or undefined title or alt attribute.

$('img').attr('alt','image here'); $('img').attr('title','pany name')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745138922a4613337.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信