display alt tag for image using this - jquery

岁酱吖の 提交于 2020-01-02 15:06:19

问题


A client wants the alt tag text to appear when hovered (and can't be convinced it should be title, alas). This is as far as I got, but I need only the hovered img's alt tag to display, rather than all of them. I tried removing 'each' but it broke (I know I'm not very good at this). How do I fix it:

$("ul.thumb li img").hover(function() {
  $(this).each(function(i, ele) {
  $("li").append("<div class=alt>"+$(ele).attr("alt")+"</div>");
      $(this).mouseleave(function(event){
      $(".alt").css('display','none');
});
});
});

Here it is in a fiddle


回答1:


$("ul.thumb li img").each(function() {
    $(this).parent('li').append($("<span/>").text($(this).attr("alt")).hide());
}).hover(function(){
  $(this).parent('li').children('span').show();
},function(){
  $(this).parent('li').children('span').hide();
});

DEMO




回答2:


You can do it in two steps:

// create the divs
$("ul.thumb li img").each(function() {
    $('<div />', {
        class: 'alt', 
        text: $(this).attr("alt")
    }).appendTo($(this).parent());
});

// toggle the divs visibility
$("ul.thumb li img").hover(function() {
    $(this).parent().children('.alt').toggle();
});
// OR attach the handler to the li element instead:
$("ul.thumb li").hover(function() {
    $(this).children('.alt').toggle();
});

DEMO




回答3:


You don't need the .each(), and you can handle the mouseleave as the second parameter to .hover():

$("ul.thumb li img").hover(function() {
    console.log(this);
    $(this).parent().append("<div class=alt>" + $(this).attr("alt") + "</div>");
}, function() {
    $(this).siblings('.alt').remove();
});

Working demo at http://jsfiddle.net/alnitak/dPVCN/

NB: I'm remove the .alt div altogether on mouseout, since otherwise it would keep appending the alt text over and over again.

A better solution might be to pre-create all of the alt divs, and then just .show() or .hide() them as appropriate.




回答4:


TheSuperTramp's solution is the best approach, but I've tweaked it slightly to improve performance.

$('img', 'ul').each(function() {
    $(this).parent().append('<div style="display:none">' + this.alt + '</div>'); 
}).bind({
    mouseenter: function() {
       $(this).siblings('div').show();
    },
    mouseleave: function() {
        $(this).siblings('div').hide();
    } 
});

Demo: http://jsfiddle.net/5dxhC/1/




回答5:


There are two problems:

  1. You are appending the div to all li elements instead of just the current one (see @cdeszaq's answer)
  2. You are hiding the newly added div on mouseleave , making all future .alt elements hidden. You should use .remove() instead of a css property on mouseout


来源:https://stackoverflow.com/questions/5806321/display-alt-tag-for-image-using-this-jquery

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