问题
I need some help, and before we get going, I know it is probably not best practice, but I am doing some maintenance to an existing site and need to accomplish the following for a fix.
<a rel="lightbox" href="site.com" title="a generated title">
<img src="site.com/img" class="post-image" alt="a long description"/>
</a>
Okay, so I am trying to figure out how to use jQuery or any other method to take the alt
attribute from my image, and dynamically overwrite the title
attribute of my a
tag.
Any help would be awesome, I am kinda lost at this juncture.
回答1:
$(function(){
$("a").each(function(){
$(this).attr("title", $(this).find("img").attr("alt"));
});
});
回答2:
you didn't mention exactly which <a>
s you wanted to change, so this would change all <a>
s with an <img>
inside...
$("a>img").each(function() {
$(this).parent().attr("title", $(this).attr("alt"))
})
回答3:
With jQuery:
var a = $('a[rel=lightbox])');
var img = a.find('img');
a.attr('title', img.attr('alt'));
回答4:
You can do it like this:
$(function() {
var img = $(".post-image");
if(img.length == 1) // meaning, at least one element was found
{
img.attr("title", img.attr("alt")); // pass the text in alt to title
img.removeAttr("alt"); // remove alt
}
});
回答5:
$('a').each(function(){
$(this).attr('title',$(this).find('img').attr('alt'));
});
Since jsFiddle.net seems to be flaky over the last day or so, you can see a demo at jsbin.
And if jsFiddle loads, a jsFiddle example.
来源:https://stackoverflow.com/questions/11247658/use-alt-value-to-dynamically-set-title