4

我正在尝试检索标题属性并用它替换当前段落文本。关于我的脚本的其他所有内容都运行良好。标题属性返回为“未定义”。我是 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>
4

4 回答 4

12

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

var photo_caption = $('img', this).prop('title');
于 2012-08-29T21:25:02.677 回答
12

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

尝试:

$('img', this).attr('title');
于 2012-08-29T21:25:04.197 回答
5

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

于 2012-08-29T21:25:28.800 回答
2

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

通过 chrome 和 f12 开发人员面板尝试一下。您可以在 javascript 代码中设置断点并随时检查确切this的内容。

于 2012-08-29T21:26:12.787 回答