JQuery - 结合切换悬停与on

时间:2012-10-29 16:00:28

标签: jquery

如何将切换悬停与on事件结合使用?代码:

img.on('hover', function(){
            name = $(this).attr('title');
            function(){
              $(this).parent().append('<figcaption>' + name);
            },
            function(){
              $(this).find('figcaption').remove();
            }
          });

3 个答案:

答案 0 :(得分:2)

您必须将其拆分为mouseentermouseleave

img.on('mouseenter', function() {
    name = $(this).attr('title');
    $(this).parent().append('<figcaption>' + name);
}).on('mouseleave', function() {
    $(this).find('figcaption').remove();
});

这是hover包含在单个函数中的内容。

答案 1 :(得分:0)

你没有关闭figcaption元素,你只是附加一些带有起始元素和一些文本的随机字符串,而是将其创建为jQuery对象。此外,figcaption元素附加到this父级,这将使其成为兄弟而不是孩子,因此find内的this将无法找到它,您要么必须查看对于兄弟元素或在父元素中搜索(应该是一个图元素):

img.on({
    mouseenter: function() {
        var name = $(this).attr('title'),
            figcaption = $('<figcaption />', {text: name});
        $(this).parent().append(figcaption);
    },
    mouseleave: function() {
        $(this).parent().find('figcaption').remove();
    }
});

答案 2 :(得分:-1)

.on()只能有一个回调函数。因此,您必须同时指定.on('mouseenter', ...).on('mouseleave', ...)以使用.on()模仿.hover()行为。