无法在已添加的 html、jquery 内添加 html append()

Can't add html inside already added html, jquery append()

我正在尝试添加 html 和 .append() 里面已经添加了 html,但它不起作用... 如果 html 已经存在(如果我没有添加一些),那么我可以在其中添加一些,但是如果我添加 html 并尝试在添加的 html 中添加一些 html =21=],那就不行了,我也不明白... 希望有人能帮我解决这个问题。 谢谢。 这是我的代码

<div class="add_episodes">
    <div class="season_episode">
        <input type="text">
        <input type="text">
        <input type="file" name="episode_image">
        <div class="subtitle_out"></div>
        <div class="btn-addsubtitle">add subtitle</div>
    </div>
</div>
<button id="btn-addepisode">add episode</button>

$(document).ready(function() {

  var counter = 1;

  $("#btn-addepisode").click(function(e) {
    e.preventDefault();
    $(".add_episodes").append('<div class="add_episode_out"><div class="season_episode"><input type="text" placeholder="Episode titel"><input type="text" placeholder="Indtast filnavn på episoden f.eks. orphan_black"><input class="fileextension_movie_season" type="text" placeholder=".mp4" disabled><input type="file" name="episode_image"><div class="subtitle_out"></div><div class="btn-addsubtitle">add subtitle</div><i class="fa fa-trash delete-episode"></i></div></div>');
    counter = counter + 1;
    initRemove();
  });

  var initRemove = function() {
    $(".delete-episode").click(function() {
      $(this).closest('.add_episode_out').find(".season_episode").remove();
      counter = counter - 1;
      if(counter < 1) {
        counter = 1;
      }
    });
  }

});

$(document).ready(function() {

  var counter = 1;

  $(".btn-addsubtitle").click(function(e) {
    e.preventDefault();
    $(this).closest('.season_episode').find(".subtitle_out").append('<div class="add_subtitle_out"><div class="add_subtitle"><input type="text" placeholder="Undertekstsprog"><i class="fa fa-trash delete-subtitle"></i><h5>Vælg undertekstfil (filtype .vtt)</h5><input type="file"></div></div>');
    counter = counter + 1;
    initRemove();
  });

  var initRemove = function() {
    $(".delete-subtitle").click(function() {
      $(this).closest('.add_subtitle_out').find(".add_subtitle").remove();
      counter = counter - 1;
      if(counter < 1) {
        counter = 1;
      }
    });
  }

});

Codepen example here

这是因为您将点击事件绑定到 document.ready 上的元素,但是您的新元素是在这之后创建的。您必须将点击事件重新绑定到新创建的元素,或者更好的是,只需通过 onclick.

从按钮调用函数

只需更改以下内容即可使用委托事件:

$(".btn-addsubtitle").click(function(e) {

收件人:

$('.add_episodes').on('click', '.btn-addsubtitle', function(e) {

这就是在 DOM 就绪后将事件处理程序附加到添加到 DOM 的元素的方式。

.live() | jQuery API Documentation

$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+

DEMO

And the code can be cleaned up a bit

我认为这是因为您的代码 运行ning 已准备好文档。而是使用:

$('body').on("click", '.btn-addsubtitle', function(){
alert("hi");
});

这应该 运行 *在 * 元素创建之后