小编Aja*_*wat的帖子

如何在动态附加的元素上附加点击事件?

我已经使用HTML和CSS发出了一些警报,我想通过jQuery添加和删除这些警报,但是问题是当按下关闭按钮时,我无法关闭动态添加的警报。

我也搜索了google和stack-overflow,但是我还不了解他们的工作方式,如果您能给我一些解释的答案,我将不胜感激。

$(document).ready(function() {

    // remove alert
    $(".close").on("click", function() {
        $(this)
            .parent(".alert")
            .slideUp(250)
            .promise()
            .done(function() {
                $(this).remove();
            });
    });

    // append alert
    const btn = $("#btn");
    btn.on("click", function() {
        $($(".alert")[$(".alert").length - 1])
            .after(
                '<div class="alert -ugly"> <header> Dynamically added</header> <div class="close"><img src="https://res.cloudinary.com/ajayrawat/image/upload/v1514205869/close_df3rub.svg" /> </div></div>'
            )
            .hide()
            .slideDown(250);
    });
});
Run Code Online (Sandbox Code Playgroud)
body {
  background-color: #ddd;
  font-family: sans-serif;
  font-size: 14px;
  letter-spacing: 1px;
}

.alert {
  display: block;
  position: relative;
  width: 100%;
  max-width: 30rem;
  padding: .5rem .8rem;
  margin: 1rem auto 0;
  border-radius: .2rem;
  color: …
Run Code Online (Sandbox Code Playgroud)

html jquery

3
推荐指数
1
解决办法
552
查看次数

标签 统计

html ×1

jquery ×1