Trouble with .attr('title')

Trouble with .attr('title')

本文关键字:title with attr Trouble      更新时间:2023-09-26

我正在尝试检索title属性并用它替换当前段落文本。我的脚本的其他一切都很好。title属性返回为"未定义"。我是javascript的新手,我已经到处寻找答案。。。到目前为止我没有看到任何东西。

JS:

$(document).ready(function(){
    $('.thumbnails a').click(function(e){
        e.preventDefault();
        $('.thumbnails a').removeClass('selected');
        $('.thumbnails a').children().css('opacity','1');
        $(this).addClass('selected');
        $(this).children().css('opacity','.4');
        var photo_caption = $(this).attr('title');
        var photo_fullsize = $(this).attr('href');
        var photo_preview = photo_fullsize.replace('_large','_preview');
        $('.preview').html('<a href="'+photo_fullsize+'" title="'+photo_caption+'" style=background-image:url('+photo_preview+')></a>');
        $('.caption').html('<p><a href="'+photo_fullsize+'" title="'+photo_caption+'">View larger</a></p><p>'+photo_caption+'</p>');
    });
});

HTML:

<li>
   <a href="images/webdesign/indiePantry_large.jpg" target="_blank">
      <img src="images/webdesign/indiePantry_thumbnail.jpg" 
             width="160" height="160" title="Indie Pantry" />
   </a>
</li>

在代码中,this引用a标记,而不是图像。

尝试:

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

标题在图像上,而不是<a>元素:

var photo_caption = $('img', this).prop('title');

您使用的是this,但在您的代码中,this指的是没有title属性的<a>。您需要使用$(this).find('img').attr('title');

this是您的a标签,而a没有title(img有)

通过chrome和f12显影剂面板进行尝试。您可以在javascript代码中设置断点,并随时检查this到底是什么。