HTML code:
$(".imageupload").change(function() {
alert($(this).attr('data-id'));
var ID = $(this).attr('data-id');
if (typeof(FileReader) != "undefined") {
var image_holder = $("#image-holder" + ID);
image_holder.empty();
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-6 col-md-3">
<div id="image-holder1" style="margin-bottom:20px"> </div>
<input type="file" class="input-file full-width imageupload" data-id="1" name="imageupload1" id="imageupload1" value="" placeholder="">
<div id="displayimagefield">
<div id="image-holder2" style="margin-bottom:20px"> </div>
<input type="file" class="input-file full-width imageupload" data-id="2" name="imageupload2" id="imageupload2" value="" placeholder="">
<div id="image-holder3" style="margin-bottom:20px"> </div>
<input type="file" class="input-file full-width imageupload" data-id="3" name="imageupload3" id="imageupload3" value="" placeholder="">
</div>
</div>
class imageupload是多个元素。更改事件仅在data-id =“1”中触发,而不是在其他任何地方触发。我该如何解决这个错误?抱歉我的英语不好。
答案 0 :(得分:0)
将附件事件的事件委派用于动态添加的元素:
$("body").on('change','.imageupload',function() {
//CHANGE EVENT CODE HERE
});