gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:05:28 25 4
gpt4 key购买 nike

我采用类“.follow”的 img 元素,然后隐藏它并将其替换为新创建的类 .followbutton 的元素按钮。在 mouseout 事件之后,我将这个新创建的按钮元素隐藏起来,并将其替换为新创建的带有 .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 上丢失了监听器。您必须改用事件委托(delegate)。

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

关于javascript - jQuery 事件不适用于新创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39116660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com