I have this HTML markup
<a href="#" title="">
<img src="#" title="image1" />
</a>
<a href="#" title="">
<img src="#" title="image2" />
</a>
<a href="#" title="">
<img src="#" title="image3" />
</a>
and I need to take the title of each image and put it on their "a". I trie开发者_如何转开发d to do it with this function
$(function() {
var title = $('a').find('img');
var updateTitle = title.attr('title');
$('a').attr({
title: updateTitle,
alt: 'lol'
});
});
But the only result is the same title for all "a" (the first title he finds)
Any help????
Thank you very much
$(function() {
$('a > img').each(function() {
this.parentNode.title = this.title;
this.parentNode.alt = 'lol';
});
});
or
$(function() {
$('a:has(img)').attr('title', function() {
return $(this).children('img').attr('title');
}).attr('alt', 'lol');
});
Try this:
$('a').each(function() {
var title = $(this).find('img');
var updateTitle = title.attr('title');
$(this).attr({
title: updateTitle,
alt: 'lol'
});
};
The attr() method only acts on the first element of the wrapped set. The same applies for other jQuery methods as well. Using the each utility method is very convenient for cases like this.
Here is modified function. You have to loop through each anchor tag and update its attributes accordingly
$('a').each(function(){
var title = $(this).find('img');
var updateTitle = title.attr('title');
$(this).attr({
title: updateTitle,
alt: 'lol'
});
});
Use the callback signature of attr
:
$(function(){
$('a').attr('title', function() {
return $(this).find('img').attr('title');
});
});
Edited to work reliably Note that this is less efficient than patrick dw's version.
精彩评论