gpt4 book ai didi

javascript - JQuery 事件未触发以淡出警报框

转载 作者:行者123 更新时间:2023-11-30 12:22:21 26 4
gpt4 key购买 nike

这个问题有点困扰我。应该是一个非常简单的解决方案,但我不太明白。我正在做的是通过 Jquery 创建几个嵌套元素,然后使用 JQuery.fade() 方法将其从页面中删除。

创建的元素上的关闭按钮不会触发事件,但如果应用于独立按钮,它会起作用。

Javascript:

$( document ).ready(function() {

$("button.create").click(function(){
// action goes here!!
// $(".alertBox").fadeIn();
$('.alerts').append('<div class="alertBox"><span class="hide"><a href="#">X Close</a></span><p><strong>Alert!</strong> Thank you for submitting your comment. Scroll to the bottom of the page to view it.</p></div>');
return false;
});

$("button.close").click(function(){
// action goes here!!
$(".alertBox").fadeOut();
return false;
});

$(".hide").click(function(){
// action goes here!!
alert("check check");
$(".alertBox").fadeOut();
});

});

HTML:

<h1>Fun with Alert Boxes</h1>
<p>This page is to test the ability to add or remove alert boxes from the DOM. By clicking on the button below, you will make an alert box appear and then you will be able to close the alert box with a button in the top right corner. This will all rely on JQuery to add and remove content from the DOM.<p>

<div class="alerts"></div>

<p>&nbsp;</p>
<button class="create">Create Alert</button>
<button class="close">Destroy Alert</button>

我有一个 Fiddle for it http://jsfiddle.net/coolwebs/5n5nosdc/4/ - 我已经用控制台日志检查过它,看不到任何明显的错误。显然,问题是因为函数是在元素在页面上可用之前声明的,这是否可能就是它不起作用的原因?

更新:通过动态生成脚本进行了一些测试,证明了我的怀疑。

最佳答案

对动态创建的元素使用事件委托(delegate)

$('.alerts').on('click', '.hide', function(){
// action goes here!!
alert("check check");
$(".alertBox").fadeOut();
});

供大家引用学习Event Delegation in SO

关于javascript - JQuery 事件未触发以淡出警报框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30588847/

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