0
<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>

After dynamically creating the list of image tags, i am not able to select images or store them in the data array. how can make this to work?

4

3 回答 3

1

如果要为动态生成的元素添加任何事件,则需要使用 event 添加/绑定所需的on事件。

例如。

$("#layers_list").on('click', "li img", function(){
//code goes here..
})
于 2013-06-05T09:56:26.487 回答
1

对动态创建的元素使用事件委托:

$(document).on('click', '#layers_list li img', function(){
    $(this).data('select', true);     //add images on click
    console.log("clicked");              
});
于 2013-06-05T09:52:48.750 回答
0

改变

$("#layers_list li img").click(function(){

$("#layers_list").on('click', "li img", function(){
于 2013-06-05T09:53:31.410 回答