简体   繁体   中英

jQuery Add Image Title Attribute from Alt

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 () {
    $this = $(this);
    if (!$this.attr('title') && $this.attr('alt')) {
        $this.attr('title', $this.attr('alt'));
    }
})
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 .

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

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','company name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM