jQuery('img').each(function() {
jQuery(this).attr('title', jQuery(this).attr('alt'));
})
我该如何修改上面的代码,以便仅在 alt 中应用 title 属性,如果它还没有 title 属性的话?换句话说,如果图像已经有一个非空的 title 属性,则此代码不应执行。
jQuery('img').each(function() {
jQuery(this).attr('title', jQuery(this).attr('alt'));
})
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'));
})
通过使用条件来检查'alt'属性是否存在:
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'));
});
你也可以使用 .attr() 的 setter 版本,例如:
jQuery('img').attr('title', function () {
if (!this.title) {
return this.alt
}
})
演示:Fiddle
这应该能解决问题。
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属性的图像。
$('img').attr('alt','这里放图片'); $('img').attr('title','公司名称')
jQuery('img:not([title!=""][title])').each(function() { jQuery(this).attr('title', jQuery(this).attr('alt')); })
- Kailash Yadav