开发者

Reading the IMG within an A on click jQuery

I'm trying to adapt my script to read the alt attribute of an img within an a.

For some reason, this isn't work:

$("#thumbs a").click(function(event) {
    event.preventDefault();
    var title = $(this + " img").attr("alt");
    alert(title);
}开发者_如何学C);

It returns a value of [object Object].

I'd appreciate some help, thanks.


You need to change your selector to use the second parameter, which is the context in which to evaluate the selector.

$("#thumbs a").click(function(event) {
    var title = $('img', $(this)).attr("alt");
    alert(title);
});

Working example: http://jsfiddle.net/q4Bsq/2/


$(this + " img") will not select anything so the alert which you are seeing is just an empty jQuery object. You should using $(this).find("img") which will select all the img elements within this i.e the anchor element in this case.

$("#thumbs a").click(function(event) {
    event.preventDefault();
    var title = $(this).find("img").attr("alt");
    alert(title);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜