<form id="upload_form" action="" method="post">
<label for="file_input">Select Files to Upload:</label>
<input id="file_input" type="file" multiple>
</form>
</p>
<input id="add" type="submit" value="add to canvas" >
<div id="layers_list" class="layers_col" ></div>
<script>
$(document).ready(function(){
var file_input = $('#file_input');
var layers_list = $('#layers_list');
file_input.on('change',onFilesSelected);
function onFilesSelected(event){
var files = event.target.files;
for(var i= 0;i<files.length; i++){
var img = $("<img/>").attr("src",URL.createObjectURL(files[i]));
img.attr("title", files[i].name);
var heading = $("<h3></h3>").text(files[i].name.substr(0,12));
$("<li></li>").append(img).append(heading).appendTo(".layers_col");
}
}
$("#layers_list li img").click(function(){
$(this).data('select',true); //add images on click
console.log("clicked");
});
$("#add").click(function(){
var selectedImgs = [];
$("#layers_list li img").each(function(){
$(this).data("select")? selectedImgs.push(this.name):false; //choose //selected images
});
alert(selectedImgs.join(','));
});
});
</script>
动态创建图像标签列表后,我无法选择图像或将其存储在数据阵列中。怎么能让这个工作?
答案 0 :(得分:1)
将event delegation用于动态创建的元素:
$(document).on('click', '#layers_list li img', function(){
$(this).data('select', true); //add images on click
console.log("clicked");
});
答案 1 :(得分:1)
如果要为动态生成的元素添加任何事件,则需要使用on
事件添加/绑定所需事件。
例如
$("#layers_list").on('click', "li img", function(){
//code goes here..
})
答案 2 :(得分:0)
更改
$("#layers_list li img").click(function(){
到
$("#layers_list").on('click', "li img", function(){