【问题标题】:Jquery if hover element add a button if not remove buttonJquery如果悬停元素添加一个按钮如果不删除按钮
【发布时间】:2017-07-15 05:41:35
【问题描述】:

我在 jquery 中添加一个带有 append 的按钮,bot 我遇到了 2 个问题

1- 每次悬停时都会添加此按钮。

2 - 当没有悬停按钮时仍然存在。

$('#user tbody tr td').hover(function() {
   $(this).addClass('hover2').append('<button>add user</button>');
}, function() {
 $(this).removeClass('hover2').remove('<button>add user</button>');
});

【问题讨论】:

  • 请添加您的html代码
  • 为什么不在 HTML 中创建 &lt;button&gt; 并使用 css 的 :hover 伪类简单地显示和隐藏它?这有一些优势,因为您不必在每次重新创建新创建的元素时都将事件处理程序重新附加到它。

标签: jquery hover jquery-hover mousehover


【解决方案1】:

使用 mouseenter/mouseleave 事件

$('#user tbody tr td').mouseenter(function() {
   $(this).addClass('hover2').append('<button>add user</button>');
}).mouseleave(function() {
 $(this).removeClass('hover2').find('button').remove();
});

演示:

$('#user tbody tr td').mouseenter(function() {
   $(this).addClass('hover2').append('<button>add user</button>');
}).mouseleave(function() {
 $(this).removeClass('hover2').find('button').remove();
});
.hover2 {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="user"><tbody><tr><td>mouse</td></tr></tbody></table>

【讨论】:

    【解决方案2】:

    您添加的内容和删除的内容不匹配。您应该以某种方式找到您之前添加的元素并将其删除。

    $('#user tbody tr td').hover(function() {
       $(this).addClass('hover2').append('<button>add user</button>');
    }, function() {
     $(this).removeClass('hover2').find('button').remove();
    });
    

    【讨论】:

      【解决方案3】:
      $('#user tbody tr td').hover(function() {
         $(this).addClass('hover2').append('<button>add user</button>');
      }, function() {
       $(this).removeClass('hover2').find('button').remove();
      });
      

      使用&lt;div&gt; 元素的示例

      http://jsfiddle.net/xtb51wed/1095/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-08
        • 1970-01-01
        • 1970-01-01
        • 2012-08-02
        • 2012-11-05
        • 2013-01-17
        • 2019-06-07
        相关资源
        最近更新 更多