jQuery .on委托mouseenter mouseleave无效

时间:2016-02-29 19:43:59

标签: jquery

它将在第一个动态创建的链接上工作,但它不适用于其他链接。此外,弹出信息在出于某种原因悬停之前已经显示。这就是我所拥有的:

<div id="parent">
<a href="" id="hovertitle">Hover Text</a>
</div>

<div id="popup">
    testing 123
</div>

这是我的jfiddle,包括jquery链接http://jsfiddle.net/2XG9j/1/ 它适用于jfiddle,但是当我用动态对象运行它时,它对其他链接不起作用。

1 个答案:

答案 0 :(得分:1)

尝试使用.next().toggle();在display:none处为className"popup"开头的元素设置css;将事件附加到选择器"[class^=parent]"className"parent"

开头的元素

&#13;
&#13;
$(document)
.on("mouseenter", "[class^=parent]", function(e) {
  $(this).next("[class^=popup]").toggle()
})
.on("mouseleave", "[class^=parent]", function(e) {
  $(this).next("[class^=popup]").toggle()
});
&#13;
div[class^="parent"] {
  border: 2px solid green;
  padding 4px;
}
div[class^="popup"] {
  border: 2px solid red;
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="parent">
  <a href="" id="hovertitle">Hover Text</a>
</div>

<div class="popup">
  test
</div>

<div class="parent2">
  <a href="" id="hovertitle">Hover Text</a>
</div>

<div class="popup2">
  test 2
</div>
&#13;
&#13;
&#13;

jsfiddle http://jsfiddle.net/2XG9j/5/

请注意,在问题html处,使用css :hover,下一个同级+选择器,而不使用javascript

&#13;
&#13;
div[class^="parent"] {
  border: 2px solid green;
  padding 4px;
}
div[class^="popup"] {
  border: 2px solid red;
  display: none;
}
div[class^="parent"]:hover + div[class^="popup"] {
  display: block;
}
&#13;
<div class="parent">
  <a href="" id="hovertitle">Hover Text</a>
</div>

<div class="popup">
  test
</div>

<div class="parent2">
  <a href="" id="hovertitle">Hover Text</a>
</div>

<div class="popup2">
  test 2
</div>
&#13;
&#13;
&#13;

jsfiddle http://jsfiddle.net/2XG9j/6/