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

Cod*_*der 1 html jquery

我在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"/>
Run Code Online (Sandbox Code Playgroud)

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

<script type="text/javascript">

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

</script>
Run Code Online (Sandbox Code Playgroud)

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

Aru*_*hny 6

this在你的代码中没有引用img元素.您需要使用以回调作为参数.attr() setter

jQuery(function(){
    $('img').attr('title', function(){
        return $(this).attr('alt')
    });
})
Run Code Online (Sandbox Code Playgroud)

  • @ 3dgoo总会有改进的余地,所以只是想知道如果他/她知道更好的方法,我是否错过了dowonvoter的任何内容 (2认同)