Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

javascript - Binding event to dynamically created elements using jQuery

I am uploading multiple images and placing them inside some divs which onclick have to toggle some class. Do I have to place the part in which I add the onclick event inside the ajax success function? Thanks a lot!

I am using the jquery "on", but doesn't seem to work . Probably I'm missing something

Here is my code:

Javascript:

$(".box-picture-selected > div > div").on( 'click' , function () {
    $(this).toggleClass('image-selected');
});

$('#uploadForm').submit(function (e) {
    e.preventDefault();

    var form = new FormData($('form')[0]);
    var files = document.getElementsByClassName('pics');
    for (var i=0; i<files.length; i++) {
        form.append("files[" + i + "]", files[i][0]); // add receipt to form
    }
    form.append('action', 'upload-photos'); // specify action
    form.append('csrfmiddlewaretoken', '{{ csrf_token() }}');
    $.ajax({
        url: '{{url("/photos/device")}}',
        type: 'POST',
        data: form,
        cache: false,
        processData: false,
        contentType: false,
        success:function(data) {
            $.each($(data), function(key, value) {
                var displayDiv = document.getElementById("displayPics");
                var grid = document.createElement("div");
                grid.setAttribute("class", 'col-md-3 col-sm-4 col-xs-6 grid-changes image-selected');
                var picDiv = document.createElement("div");
                picDiv.setAttribute("class" , 'col-xs-12 images-box');
                picDiv.setAttribute("style", 'background-image: url({{ url('fit/?image='.urlencode(asset('filestorage/temp'))) }}' + '%2F' + value + ');'  );
                displayDiv.appendChild(grid);
                grid.appendChild(picDiv);
            });
        },
        error: function(xhr, desc, err) {
            // I have some error handling logic here
        }
    });
});    

HTML:

<div id="displayPics" class="col-xs-12 grid-4-picture">
      @if (isset($files) && !empty($files))
          @foreach ($files as $photo)
              <div class="col-md-3 col-sm-4 col-xs-6 grid-changes">
                  <div class="col-xs-12 images-box" style="background-image: url({{ url('fit/?image='.urlencode(asset('filestorage/temp/'.$photo))) }});"></div>
                  <input type="hidden" value="{{ url('fit/?image='.urlencode(asset('filestorage/temp/'.$photo))) }}">
             </div>
          @endforeach
       @endif
    </div>  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For dynamically created element you have to use .live() However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

If you have greater version of jQuery than 1.9 you can use jQuery.fn.on

I would recommend to use .on below is a signature of .on function

$(document).on( eventName, selector, function(){} );

$("body").on("click", "#YOUR_DYNAMICALLY_CREATED_ELEMENT", function(event){
    //Do Some stuff
});

Solved version:

$("body").on('click', '.box-picture-selected > div > div', function(event)
{
    $(this).toggleClass('image-selected');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...