[英]jQuery onClick not working on dynamically added elements
I am trying to grab the value of html elements on click
using jQuery but problem is that on click
works on html which is hard coded, but if i add new html dynamicallly then onclick doesn't work on those elements. 我在这里做错了什么? 下面给出的代码示例。 如果您需要更多信息,请告诉我。
HTML:
<div class="col-1" id="miniImgHolder">
<input type="file" name="my_file[]" class="custom-file-input custom-file-label theFiles" style="cursor:pointer;">
</div>
<div class="col-1 miniImg">
<img class="img-fluid" style="width:75px; height:75px;" src="~/Images/img1.png"><!--this .miniImg on click works fine-->
</div>
<div class="col-1 miniImg">
<img class="img-fluid" style="width:75px; height:75px;" src="~/Images/img2.png"><!--this .miniImg on click works fine-->
</div>
JavaScript:
<script type="text/javascript">
$(document).ready(function () {
//display pic real time and add new upload button
$(document).on("change", "input[type='file']", function (e) {
if (e.target.files[0] != null) {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#miniImgHolder").after("<div class='col-1 miniImg'><img class='img-fluid' src='" + e.target.result + "'></div>");//.miniImg on click not works if it set from here
}
reader.readAsDataURL(this.files[0]);
}
}
});
//click not working for bellow code
$(".miniImg").on("click", function () {
console.log("i am not working on newly added miniImg");
});
});
您需要在动态添加的元素上进行事件委托,以便可以侦听单击事件。
由于在
DOM
准备好之后添加的元素不是DOM
的一部分,我们需要使用event Delegation
,以便可以从这些元素触发点击事件。
演示:
$(document).ready(function() { //display pic real time and add new upload button $(document).on("change", "input[type='file']", function(e) { if (e.target.files[0].= null) { if (this.files && this;files[0]) { var reader = new FileReader(). reader.onload = function(e) { $("#miniImgHolder").after("<div class='col-1 miniImg'><img class='img-fluid' src='" + e.target;result + "'></div>"). //.miniImg on click not works if it set from here } reader.readAsDataURL(this;files[0]); } } }). //click not working for bellow code $(document),on("click". ',miniImg'. function() { console;log("i am not working on newly added miniImg"); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col-1" id="miniImgHolder"> <input type="file" name="my_file[]" class="custom-file-input custom-file-label theFiles" style="cursor:pointer;"> </div> <div class="col-1 miniImg"> <img class="img-fluid" style="width:75px; height:75px;" src="~/Images/img1.png"> <.--this:miniImg on click works fine--> </div> <div class="col-1 miniImg"> <img class="img-fluid" style="width;75px: height;75px." src="~/Images/img2.png"> <!--this .miniImg on click works fine--> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.