悬停后删除标签

时间:2014-11-19 08:11:18

标签: javascript jquery

我使用以下代码在我的子菜单中添加行:

$("li.mega-menu-megamenu a").hover(function(){ 
    $( "<div class='remove'><hr /></div>" ).insertAfter("#mega-menu-primary-2 li:last-child" );
});

它的工作非常精细。但问题是我想在没有悬停时删除该标签。

我试过这个:$("li.mega-menu-megamenu a").unbind('hover');但是通过这样做,它根本不会添加html标签。

如果菜单上没有悬停,如何删除行?

4 个答案:

答案 0 :(得分:0)

您可以使用mouseout事件

$("li.mega-menu-megamenu a").mouseout(function() {
    $(".remove").remove();
});
$("li.mega-menu-megamenu a").mouseenter(function() {
    $("<div class='remove'><hr /></div>").insertAfter("#mega-menu-primary-2 li:last-child");
});

另一种可能的解决方案是,您可以隐藏/显示元素,而不是添加和删除元素。

$(document).ready(funnction() {
    $("<div class='remove'><hr /></div>").insertAfter("#mega-menu-primary-2 li:last-child");
    $(".remove").hide();
    $("li.mega-menu-megamenu a").mouseout(function() {
        $(".remove").hide();
    });
    $("li.mega-menu-megamenu a").mouseenter(function() {
        $(".remove").show();
    });
});

答案 1 :(得分:0)

我会选择隐藏/显示,因此您不会继续添加/删除DOM。

// Add the element to the DOM once and then hide it
var $removeElement = $( "<div class='remove'><hr /></div>" )
    .insertAfter( "#mega-menu-primary-2 li:last-child" )
    .hide();

// On mouseover we show the $removeElement and mouseout will hide it
$("li.mega-menu-megamenu a")
    .hover(function(){ $removeElement.fadeIn();  },
           function() { $removeElement.fadeOut(); }
     );

我使用了fadeIn / fadeOut,但如果愿意,你可以使用show / hide。

答案 2 :(得分:0)

您可以将2个功能传递给悬停。当鼠标退出元素时,将调用秒。

$("li.mega-menu-megamenu a").hover(function() {
  $("<div class='remove'><hr /></div>").insertAfter("#mega-menu-primary-2 li:last-child");
},
function() {
  $(".remove").remove();
});

答案 3 :(得分:0)

另一种方式:

$('li.mega-menu-megamenu a').on({
    'mouseenter':function(){
       $("<div class='remove'><hr /></div>").insertAfter("#mega-menu-primary-2 li:last-child");
    },'mouseleave':function(){
        $(".remove").remove();
    }
});