Trouble with .attr('title')
Trouble with .attr('title')
我正在尝试检索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
到底是什么。
相关文章:
- Fighting with FRP
- issue with FB.Event.subscribe
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- WebComponentsJS with IE10
- 指令的模板必须只有一个根元素:With restrict E&替换true
- timeago.js with datatable and PHP
- Ajax and Json with Rails
- errors with Javascript try catch
- how to split a string with ','
- Understanding Javascript scope with "var that = this&qu
- Architecture for CPU intensive tasks with NodeJS & Socke
- How to declare a Map containing certain properties with flow
- 设置'这'在React with Inverse Data Flow中
- Unit-testing multiple use cases with Karma & Mocha.js
- Modify Javascript with C#
- 谷歌地图API v3:Initial View is Fine,but Gray Box with No Map if
- Trouble with .attr('title')
- s.split with TITLE don'不起作用