繁体   English   中英

jQuery事件不适用于新创建的元素

[英]jQuery event doesn't work at new created element

我将img元素与“ .follow”类一起使用,然后将其隐藏,并使用“ .followbutton”类将其替换为新创建的元素按钮。 在“ mouseout”事件之后,我将这个新创建的button元素隐藏起来,并将其替换为具有“ .follow”类的新创建的img元素。 最终,我得到了具有与最初相同属性的新元素img。 但是现在“ mouseenter”不起作用。 而且我不知道为什么。

 $(".follow") .on("mouseenter", function() { $(this).fadeOut(150, function() { var init = this; var btn = document.createElement("BUTTON"); var t = document.createTextNode("Follow"); btn.appendChild(t); btn.className = "followbutton"; $(btn).hide(); $(this).replaceWith(btn); $(".followbutton").show(150); $(".followbutton").on("mouseout", function() { var imgback = $("<img />", { class: "follow", src: "img/remove.png", }).hide(); $(this).hide(150); $(this).replaceWith(imgback); $(".follow").show(150); }); }); }); 
 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="script.js"></script> <title>Follow</title> </head> <body> <img src="img/remove.png" class="follow"> </body> </html> 

因为在创建新的img标记并将其替换为文档时,您在.follow上丢失了侦听器。 您必须使用事件委托。

$(document).on("mouseenter", ".follow", function() { /* ... */ });

 $(document).on("mouseenter", ".follow", function() { $(this).fadeOut(150, function() { var init = this; var btn = document.createElement("BUTTON"); var t = document.createTextNode("Follow"); btn.appendChild(t); btn.className = "followbutton"; $(btn).hide(); $(this).replaceWith(btn); $(".followbutton").show(150); $(".followbutton").on("mouseout", function() { var imgback = $("<img />", { class: "follow", src: "img/remove.png", }).hide(); $(this).hide(150); $(this).replaceWith(imgback); $(".follow").show(150); }); }); }); 
 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="script.js"></script> <title>Follow</title> </head> <body> <img src="img/remove.png" class="follow"> </body> </html> 

如果将事件附加到新添加的项目,则不会发生任何事情。 这是因为我们之前附加了直接绑定的事件处理程序。 直接事件仅在调用.on()方法时附加到元素。 请参考下面的链接以获取示例并清楚理解。

https://learn.jquery.com/events/event-delegation/

您可以在这种情况下使用委托。 它将解决事件附加到元素的问题。 尝试下面的代码。

$(document).delegate(".follow","mouseenter", function() {
    //YOUR CODE
});

暂无
暂无

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

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