繁体   English   中英

jQuery悬停功能无法在动态添加的元素上运行

[英]Jquery hover function doesnt run on dynamically added element

这可以成功运作,

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

但是,如果将其动态添加,则无法正常工作。 我有一个click函数,适用于动态添加的元素,

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

alert("works");

});

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

$(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

 $(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>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>GENERATE</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM