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

时间:2013-09-20 05:00:32

标签: jquery html

我在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"/>

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

<script type="text/javascript">

$('img').attr('title',$(this).attr('alt'));

</script>

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

2 个答案:

答案 0 :(得分:6)

代码中的

this未引用img元素。您需要使用.attr()

callback as the argument setter
jQuery(function(){
    $('img').attr('title', function(){
        return $(this).attr('alt')
    });
})

答案 1 :(得分:3)

试试这样。

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