[英]How to register a click on every instance of a div class in jquery?
What I'm trying to do is extremely simple.我正在尝试做的事情非常简单。 When I click on any instance of a class, create a new element of that class.
当我单击 class 的任何实例时,创建该 class 的新元素。 The problem I'm running into is even though the click of the first instance is registered, and a new element is created.
我遇到的问题是即使注册了第一个实例的点击,并创建了一个新元素。 Clicking the newly created element with that class name does not create another element.
单击具有该 class 名称的新创建元素不会创建另一个元素。 I have to always click the first element in order for the script to work.
我必须始终单击第一个元素才能使脚本正常工作。
#html
<div class="modal-body">
<div class="form-group" id="images_upload">
<input type="file" name="file" class="file">
</div>
<div class="form-group">
<input type="text" name="text" class="text" placeholder="type in a description">
</div>
</div>
#js
$(".file").click(function () {
var image = document.getElementById("images_upload");
var newInput = document.createElement("input");
newInput.type = "file";
newInput.name = "file";
$(newInput).addClass("file");
image.appendChild(newInput);
$();
});
see my codepen看我的codepen
https://codepen.io/benjermann/pen/vYgyapb?editors=1111 https://codepen.io/benjermann/pen/vYgyapb?editors=1111
This is because the element was added after the click function was bound.这是因为该元素是在点击 function 绑定后添加的。
Change it to the following and it should work.将其更改为以下内容,它应该可以工作。
$(document).on("click", ".file", function() { var image = document.getElementById("images_upload"); var newInput = document.createElement("input"); newInput.type = "file"; newInput.name = "file"; $(newInput).addClass("file"); image.appendChild(newInput); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script> <div class="modal-body"> <div class="form-group" id="images_upload"> <input type="file" name="file" class="file"> </div> <div class="form-group"> <input type="text" name="text" class="text" placeholder="type in a description"> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.