最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论
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')

发布评论

评论列表(0)

  1. 暂无评论