使用'alt'值在 img 中动态设置'title'值



我在asp中有很多图像

  <img src="site.com/img" class="post-image" alt="a long description"/>
<img src="site.com/img_1" class="post-image" alt="a long description2"/>

图像标签中没有标题。 我需要使用替代文本来设置每个图像的标题。我正在使用jquery来实现这一点

<script type="text/javascript">
$('img').attr('title',$(this).attr('alt'));
</script>

它不起作用,我错过了什么。 请帮忙。

代码

中的this不引用img元素。您需要使用将回调作为参数的 .attr() setter

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

试试这样。

$('.post-image').each(function() {
    this.title = this.alt;
})

最新更新