首页 > 解决方案 > .hover 和 .on 与 jQuery 的问题

问题描述

我在使用 jQuery.hover.on使用 jQuery 进行更改时遇到问题。

在代码中包含了一个 jsfiddle

$(".nName").hover(function() {
    $(this).css({'color': "blue", "text-decoration": "underline"});
},
function() {
    $(this).css('color', "black");
});

标签: jquery

解决方案


$(".nName").hover(function() {
  $(this).css({
    'color': "blue",
    "text-decoration": "underline"
  });
}, function() {
  $(this).css('color', "black");
});

setTimeout(function() {
  $('body').append('<div class="nName2">Dynamically rendered node1</div>')
  // The hover event will take effect here.
  /**
  $(".nName2").hover(function() {
  $(this).css({
    'color': "blue",
    "text-decoration": "underline"
  });
}, function() {
  $(this).css('color', "black");
});
**/
}, 2000)

$(".nName2").hover(function() {
  $(this).css({
    'color': "blue",
    "text-decoration": "underline"
  });
}, function() {
  $(this).css('color', "black");
});

setTimeout(function() {
  $('body').append('<div class="nName3">Dynamically rendered node2</div>')

}, 2000)

$('body').on('mouseenter', '.nName3', function() {
  $(this).css({
    'color': "blue",
    "text-decoration": "underline"
  });
});
$('body').on('mouseleave', '.nName3', function() {
  $(this).css('color', "black");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="nName">Existing node</div>

初始化页面时,无法将悬停事件绑定到动态呈现的节点。

换句话说,您可以使用mouseenterandmouseleave代替hover.


推荐阅读