Jquery悬停函数不会在动态添加的元素上运行

时间:2016-09-02 16:57:31

标签: javascript jquery

这很有效,

$('[rel=notif]').on({
    mouseenter: function () {
$(this).find('.solnotifkara').css({"opacity":"0.46"});
  },
    mouseleave: function () {
$(this).find('.solnotifkara').css({"opacity":"0.36"});
    }
});

但是,如果它动态添加,则无效。我有一个适用于动态添加元素的点击功能,

$(document.body).on('click', '[rel="like"]' ,function(){

alert("works");

});

如何让悬停功能适用于动态添加的元素?

1 个答案:

答案 0 :(得分:6)

$(document).on({
  mouseenter: function () {
    $(this).find('.solnotifkara').css({opacity:0.46});
  },
  mouseleave: function () {
    $(this).find('.solnotifkara').css({opacity:0.36});
  }
}, "[rel=notif]");  // <<<<< delegate here your dynamic element

&#13;
&#13;
$(document).on({
  mouseenter: function () {
    $(this).find('.solnotifkara').css({opacity:0.2});
  },
  mouseleave: function () {
    $(this).find('.solnotifkara').css({opacity:1});
  }
}, "[rel=notif]");  // <<<<< delegate here your dynamic element


// for test only:
$("button").on("click", function(){
  $("body").append('<p><a rel="notif">This is a <span class="solnotifkara">note</span>.</a></p>');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>GENERATE</button>
&#13;
&#13;
&#13;