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

标签 javascript jquery

这个问题有点困扰我。应该是一个非常简单的解决方案,但我不太明白。我正在做的是通过 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/

相关文章:

javascript - 检查数据库mongodb Node js中是否存在多个数据数组?

javascript - 没有 ID 的多个 Bootstrap 轮播?

javascript - 按钮单击功能在数据表工具栏自定义按钮上不起作用

php - 停止页内操作的 Jquery 模式对话框

JavaScript 未在 WKWebView 中执行

javascript - 使用js库内部缓存的数据

Javascript/ECMAScript 垃圾收集

javascript - Bootstrap 导航栏折叠 - 如何通过点击关闭

javascript - 使用 jQuery 在没有 URL 的窗口中打开 PDF

javascript - Gmap 在 js 上无法正常工作