I tried to look after a simi开发者_JAVA百科lar problem but couldn't find any here. So here is my problem. I have a structure with multiple h2. Each h2 have an image inside that points to a different url. I need to fetch this url from each image and assign it to the correspondent h2.
Here is my code (this one works, but it only fetches the first link):
$("h2").each(function() {
var $link = $('a[rel=example_group]').attr("href");
$(this).append($link);
});
So I tried this:
$("h2").each(function() {
var $link = $('a[class=button zoom]').each(function(){$(this).attr("href")});
$(this).append($link);
});
but it is not working
Could you help? Thanks
$("h2").each(function(i,n) {
var $link = $(n).find('a[rel=example_group]').attr("href");
$(n).append($link);
});
try this....
howabout
$("h2").each(function() {
var $link = $(this).find('a[class=button zoom]').attr("href")});
$(this).append($link);
});
The problem is that you are not scoping your search for the a tag.
Just cache $(this)
and do a find use it and it should work for you:
$("h2").each(function() {
var h2 = $(this),
$link = h2.find('a[rel=example_group]').attr("href");
h2.append($link);
});
In your first example you always append the same link over each iteration. Not sure what you're trying to do with the second example.
In your first example try to just add a context to your selector changing:
var $link = $('a[rel=example_group]').attr("href");
by
var $link = $('a[rel=example_group]',this).attr("href");
and it should work.
You also can do something like:
$("h2 a[rel=example_group]").each(function() {
var $link = $(this).attr('href');
// ... do what you need with $link ...//
});
It should work too if i understand well your request.
精彩评论