jQuery添加图像标题属性来自alt

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

我该如何修改上面的代码,以便仅在 alt 中应用 title 属性,如果它还没有 title 属性的话?换句话说,如果图像已经有一个非空的 title 属性,则此代码不应执行。

使用此选择器:jQuery('img:not([title!=""][title])').each(function() { jQuery(this).attr('title', jQuery(this).attr('alt')); }) - Kailash Yadav
7个回答

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

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

您可以使用此选择器,它将处理所有带有或不带有title属性的img标签,如果存在,则应为空。

0

通过使用条件来检查'alt'属性是否存在:

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

0

JS

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

0

你也可以使用 .attr() 的 setter 版本,例如:

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

演示:Fiddle


0

这应该能解决问题。

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

上述代码将跳过所有具有空标题或alt属性的图像。


0

$('img').attr('alt','这里放图片'); $('img').attr('title','公司名称')


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接