Jquery事件不使用append()中的元素

时间:2017-12-02 20:58:50

标签: javascript jquery html

目前,我创建的东西只是允许我创建任务,完成后点击它们并向左滑动以摆脱它们。 我遇到的问题是,当附加新任务时,它们不会受到脚本中任何JQuery事件的影响。

Tl; dr:追加的div不受以下javascript的影响,我该如何解决此问题?

<div class="app">

  <div class="appHeader">
    <h2>Tasks</h2>

    <form class="createTask">
      <input type="text" class="createTaskInput" size="10" maxlength="25" placeholder="Type here to create your task..." //>
    </form>

  </div>

  <div class="task">
    <div class="summary">This is an example task
      <br>When you complete a task, click the red button
      <br>Should you want to remove a task, swipe left on the task.
    </div>
    <div class="completion"></div>
  </div>
</div>


<script>
  $(".completion").on({
    'touchstart': function() {
      $(this).addClass("completed")
    }
  });

  $(document).ready(function() {
    $("div.task").on("swipeleft", swipeleftHandler);

    function swipeleftHandler(event) {
      $(event.target).addClass("swipeleft");
    }
  });

  $(document).ready(function() {
    $(".createTask").submit(function(e) {
      var value = $(".createTaskInput").val();

      $('.app').append('<div class="task"><div class="summary">' +
        value + '</div><div class="completion"></div></div>')
      e.preventDefault();
    });
  });
</script>

2 个答案:

答案 0 :(得分:1)

这是因为您在添加对象之前添加了事件侦听器。 解决方法是将事件侦听器添加到正文中。

$( "body" ).on( "swipeleft", "div.task", swipeleftHandler );

$(" body ").on( "touchstart", ".completion", function(){
  $(this).addClass("completed")
});

答案 1 :(得分:1)

因为您在添加新任务后没有绑定它们,请参阅下面的

&#13;
&#13;
function swipeleftHandler(event) {
  $(event.target).addClass("swipeleft");
}

function touchHandler(event) {
  $(event.target).addClass("completed");
}

$(document).ready(function() {

  $(".completion").on('touchstart', touchHandler);
  $("div.task").on("swipeleft", swipeleftHandler);

  $(".createTask").submit(function(e) {

    var value = $(".createTaskInput").val();
    var totalExisting = $('div.task').length;

    $('.app').append('<div class="task"><div class="summary">' + value + '</div><div class="completion"></div></div>');

    var newTask = $('div.task').eq(totalExisting);
    newTask
      .on("swipeleft", swipeleftHandler)
      .on('touchstart', touchHandler);
    e.preventDefault();
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="app">

  <div class="appHeader">
    <h2>Tasks</h2>

    <form class="createTask">
      <input type="text" class="createTaskInput" size="10" maxlength="25" placeholder="Type here to create your task..." //>
    </form>

  </div>

  <div class="task">
    <div class="summary">This is an example task
      <br>When you complete a task, click the red button
      <br>Should you want to remove a task, swipe left on the task.
    </div>
    <div class="completion"></div>
  </div>
</div>
&#13;
&#13;
&#13;