最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CSS and JQuery doesn't work after Ajax call - Stack Overflow

programmeradmin2浏览0评论

My excuses: First off all, I would like to explain that I've been searching for an answer a long time. I found so many similar questions, but none with a solution for my scenario.

The Problem: After an Ajax call, where I dinamicaly add HTML code, the code added looses its styles and action responses (on click, for example).

HTML : The HTML that is loaded with page loading. It renders the collection of the user's images correctly. I mean... the style is ok and the JS functions bind to the classes 'visualizaImagem' and 'deletaImagem' works fine.

<div class="row">
    <div class="col-sm-12" id='imagens'>
        <?php 
        if(isset($imagens)){

            if(count($imagens) > 0){

                foreach($imagens as $imagem){

                    echo "
                    <div class='file-box' data-path='" . $imagem['path'] . "' id='" . $imagem['nome'] . "'>
                        <div class='file'>
                            <a class='visualizaImagem' data-path='". $imagem['path'] ."'>
                                <div class='icon'>
                                    <img src='../" . $imagem['path'] . "' style='height:100%'>
                                    <a class='deletaImagem' data-path='". $imagem['path'] ."' data-divid='" . $imagem['nome'] . "'>
                                        <i class='fa fa-trash' style='position:absolute;top:10px;left:10px;font-size:18px;'></i>
                                    </a>
                                </div>
                                <div class='file-name'> " . $imagem['nome'] . "</div>
                            </a>
                        </div>
                    </div>";
                }
            }
        }
        ?>
    </div>
</div>

JS : When I click to the upload button (that is not part of this code), the image data is passed through "data: dados", read by "salvaImagem" in the specific controller and than appended to the page. The image is actually appended, but with no css style and no response to the functions that should have been bind to the same classes presented above.

jQuery.ajax({
        type: "POST",
        url: "salvaImagem",
        data: dados,
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){

                toastr['success'](response.msg);

                var img = "" +
                        "<div class='file-box' id='" + response.nome + "' data-path='" + response.path + "'>" +
                        "   <div class='file'>" +
                        "       <a class='visualizaImagem' data-path='"+response.path+"'>" +
                        "           <div class='icon'>" +
                        "               <img src='../"+response.path+"' style='height:100%'>" +
                        "               <a class='deletaImagem' data-path='"+response.path+"' data-divid='"+response.nome+"'>" +
                        "                   <i class='fa fa-trash' style='position:absolute;top:10px;left:10px;font-size:18px;'>" +
                        "               </a>" +
                        "           </div>" +
                        "           <div class='file-name'> "+response.nome+"</div>" +
                        "       </a>" +
                        "   </div>" +
                        "</div>";

                $('#imagens').append(img);
            }
            else{
                toastr['error'](response.msg);
            }
        });

I think I should give a little bit more about the code. Here is an example of how I bind functions to those classes. Actually as I wrote the function inside the bind, I was expecting that would't be necessary to rebind.

$('.deletaImagem').on('click', function (){
    var path = $(this).data('path');
    var div_id = $(this).data('divid');

    jQuery.ajax({
        type: "POST",
        url: "deletaImagem",
        data: {'path':path},
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){

                toastr['success'](response.msg);
                $('#'+div_id).remove();                 
            }
            else{
                toastr['error'](response.msg);
            }
        });
    return false;
});

Trying to use some of the tips friends gave me here, I tried the following, but no success either.

jQuery.ajax({
        type: "POST",
        url: "salvaImagem",
        data: dados,
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){

                toastr['success'](response.msg);

                var img = <HTML original code here>

                $(img).appendTo('#imagens').find('.deletaImagem').on('click', deletaImagem);
                $('.visualizaImagem').on('click', visualizaImagem);
            }
            else{
                toastr['error'](response.msg);
            }
        });

 function deletaImagem(){
    var path = $(this).data('path');
    var div_id = $(this).data('divid');

    jQuery.ajax({
        type: "POST",
        url: "deletaImagem",
        data: {'path':path},
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){

                $('#'+div_id).remove(); 
                toastr['success'](response.msg);
            }
            else{
                toastr['error'](response.msg);
            }
        });
    return false;
}

My excuses: First off all, I would like to explain that I've been searching for an answer a long time. I found so many similar questions, but none with a solution for my scenario.

The Problem: After an Ajax call, where I dinamicaly add HTML code, the code added looses its styles and action responses (on click, for example).

HTML : The HTML that is loaded with page loading. It renders the collection of the user's images correctly. I mean... the style is ok and the JS functions bind to the classes 'visualizaImagem' and 'deletaImagem' works fine.

<div class="row">
    <div class="col-sm-12" id='imagens'>
        <?php 
        if(isset($imagens)){

            if(count($imagens) > 0){

                foreach($imagens as $imagem){

                    echo "
                    <div class='file-box' data-path='" . $imagem['path'] . "' id='" . $imagem['nome'] . "'>
                        <div class='file'>
                            <a class='visualizaImagem' data-path='". $imagem['path'] ."'>
                                <div class='icon'>
                                    <img src='../" . $imagem['path'] . "' style='height:100%'>
                                    <a class='deletaImagem' data-path='". $imagem['path'] ."' data-divid='" . $imagem['nome'] . "'>
                                        <i class='fa fa-trash' style='position:absolute;top:10px;left:10px;font-size:18px;'></i>
                                    </a>
                                </div>
                                <div class='file-name'> " . $imagem['nome'] . "</div>
                            </a>
                        </div>
                    </div>";
                }
            }
        }
        ?>
    </div>
</div>

JS : When I click to the upload button (that is not part of this code), the image data is passed through "data: dados", read by "salvaImagem" in the specific controller and than appended to the page. The image is actually appended, but with no css style and no response to the functions that should have been bind to the same classes presented above.

jQuery.ajax({
        type: "POST",
        url: "salvaImagem",
        data: dados,
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){

                toastr['success'](response.msg);

                var img = "" +
                        "<div class='file-box' id='" + response.nome + "' data-path='" + response.path + "'>" +
                        "   <div class='file'>" +
                        "       <a class='visualizaImagem' data-path='"+response.path+"'>" +
                        "           <div class='icon'>" +
                        "               <img src='../"+response.path+"' style='height:100%'>" +
                        "               <a class='deletaImagem' data-path='"+response.path+"' data-divid='"+response.nome+"'>" +
                        "                   <i class='fa fa-trash' style='position:absolute;top:10px;left:10px;font-size:18px;'>" +
                        "               </a>" +
                        "           </div>" +
                        "           <div class='file-name'> "+response.nome+"</div>" +
                        "       </a>" +
                        "   </div>" +
                        "</div>";

                $('#imagens').append(img);
            }
            else{
                toastr['error'](response.msg);
            }
        });

I think I should give a little bit more about the code. Here is an example of how I bind functions to those classes. Actually as I wrote the function inside the bind, I was expecting that would't be necessary to rebind.

$('.deletaImagem').on('click', function (){
    var path = $(this).data('path');
    var div_id = $(this).data('divid');

    jQuery.ajax({
        type: "POST",
        url: "deletaImagem",
        data: {'path':path},
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){

                toastr['success'](response.msg);
                $('#'+div_id).remove();                 
            }
            else{
                toastr['error'](response.msg);
            }
        });
    return false;
});

Trying to use some of the tips friends gave me here, I tried the following, but no success either.

jQuery.ajax({
        type: "POST",
        url: "salvaImagem",
        data: dados,
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){

                toastr['success'](response.msg);

                var img = <HTML original code here>

                $(img).appendTo('#imagens').find('.deletaImagem').on('click', deletaImagem);
                $('.visualizaImagem').on('click', visualizaImagem);
            }
            else{
                toastr['error'](response.msg);
            }
        });

 function deletaImagem(){
    var path = $(this).data('path');
    var div_id = $(this).data('divid');

    jQuery.ajax({
        type: "POST",
        url: "deletaImagem",
        data: {'path':path},
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){

                $('#'+div_id).remove(); 
                toastr['success'](response.msg);
            }
            else{
                toastr['error'](response.msg);
            }
        });
    return false;
}
Share Improve this question edited Jun 5, 2016 at 18:58 Carlos Ost asked Jun 5, 2016 at 17:27 Carlos OstCarlos Ost 5428 silver badges26 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

Since I assume you are binding events (click etc... ) on document.ready, any new items added later will not have those events.

After adding the the new items, just add the events again.

$('#something').append("<div class='somethingWithClicklistener'>a</div>"); // It won't have the event, you have to add it
$('.somethingWithClicklistener').click(function(){ etc..

Though that approach might double the event handlers on pre-existing classes but you get the point

As for styles it shouldn't happen unless you use jquery animation etc...

if you get an ajax response as html, you have to write your javascript code relatively to your root element in witch you input your html (received from ajax).

1.

<div class="some-root-div">
    // the place where you put your html from response
</div>
  1. And you should append the html like this: $('#imagens').append($(img));

3.

(function($){
    "use strict";
    $('.some-root-div', '.deletaImagem').on('click', function(){
        // your logic on `.deletaImagem` link click
    })
})(jQuery);

Your problem is that event handlers are not being attached to the new elements. It is pretty simple to do so while you attach the element to the DOM.

Change this

$('#imagens').append(img);

to

$(img).appendTo('#imagens').find('.deletaImagem').on('click', function (){
    var path = $(this).data('path');
    var div_id = $(this).data('divid');

    jQuery.ajax({
        type: "POST",
        url: "deletaImagem",
        data: {'path':path},
        dataType: "json"}).done(function(response)
        {
            if(response.sucesso){

                toastr['success'](response.msg);
                $('#'+div_id).remove();                 
            }
            else{
                toastr['error'](response.msg);
            }
        });
    return false;
});

I've been here. My solution and understanding is that AJAX es at the end/during javascript, javascript ing way after CSS. I ended up setting the styles that need to be the most dynamic in javascript with a function that takes an element as a parameter. works like a charm!

function styleElement(elem){
    elem.style.visibility = "hidden";
}
发布评论

评论列表(0)

  1. 暂无评论