Use 'alt' value to dynamically set 'title'

十年热恋 提交于 2020-05-27 13:07:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!