jQuery onClick不处理动态添加的元素



我正试图使用jQuery获取html元素on click的值,但问题是on click适用于硬编码的html,但如果我动态添加新的html,那么onclick就不适用于这些元素。我在这里做错了什么?下面给出的代码示例。如果你需要更多信息,请告诉我。

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>

最新更新