Jquery 在 after() 事件中定位 div

Jquery target a div in after() event

我有一个很小的问题。我有一个输入字段,其中有一个按钮,可以在单击时创建它的一个实例。单击事件启动时一切正常,但是当我定位使用 after() 生成的元素时出现问题,我似乎无法做到这一点。请看下面的代码

HTML

<div class="after-add-more form-group">
    <input type="text" name="addmore[]" class="form-control" placeholder="Enter Something here">
</div>

    <!-- Copy Fields -->
<div class="copy hide">
    <div class="form-group more-duty">
        <input type="text" name="addmore[]" class="form-control try" placeholder="Enter More stuffs here">
        <button class="remove" type="button">Remove Stuff</button>
    </div>
</div>

<button class="add-more" type="button">Add Stuff</button>

Javascript

$(".add-more").click(function(){ 
     var html = $(".copy").html();
     $(".after-add-more").after(html);
});

$("body").on("click",".remove",function(){ 
     $(this).parents(".more-duty").remove();
});

$('.try').click(function() {
     alert("Ouch");
});

当我单击生成的输入以回显哎哟时,事件不是 called.please 参见 this fiddle。任何帮助将不胜感激 。谢谢 。

您需要事件委托,就像您为 .remove class 点击一样,

$("body").on("click", ".remove", function() {
  $(this).parents(".more-duty").remove();
}).on('click', '.try', function() {
  alert("Ouch");
});

$(".add-more").click(function() {
  var html = $(".copy").html();
  $(".after-add-more").after(html);
});

$("body").on("click", ".remove", function() {
  $(this).parents(".more-duty").remove();
}).on('click', '.try', function() {
  alert("Ouch");
});
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="after-add-more form-group">
  <input type="text" name="addmore[]" class="form-control" placeholder="Enter Something here">
</div>

<!-- Copy Fields -->
<div class="copy hide">
  <div class="form-group more-duty">
    <input type="text" name="addmore[]" class="form-control try" placeholder="Enter More stuffs here">
    <button class="remove" type="button">Remove Stuff</button>
  </div>
</div>

<button class="add-more" type="button">Add Stuff</button>

$(".add-more").click(function() {
  var html = $(".copy").html();
  $(".after-add-more").after(html);
});

$("body").on("click", ".remove", function() {
  $(this).parents(".more-duty").remove();
});
$(document).on("click",'.try',function() {//use .on()
  alert("Ouch");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="after-add-more form-group">
  <input type="text" name="addmore[]" class="form-control" placeholder="Enter Something here">
</div>

<!-- Copy Fields -->
<div class="copy hide">
  <div class="form-group more-duty">
    <input type="text" name="addmore[]" class="form-control try" placeholder="Enter More stuffs here">
    <button class="remove" type="button">Remove Stuff</button>
  </div>
</div>

<button class="add-more" type="button">Add Stuff</button> Javascript

它是动态添加的所以使用.on()

$ ( "body" ).on( "点击 ", ".try ", 函数( ) {

     alert( " Ouch " );

});

/**这会起作用。在您的情况下,它不起作用,因为点击事件未与元素绑定,因为它是在之后生成的*/