简体   繁体   English

Ajax调用后CSS和JQuery不起作用

[英]CSS and JQuery doesn't work after Ajax call

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). 问题:在Ajax调用之后,我在动力学上添加了HTML代码,添加的代码失去了样式和动作响应(例如,单击)。

HTML : The HTML that is loaded with page loading. HTML:页面加载时加载的HTML。 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. 我的意思是...样式还可以,并且JS函数绑定到类'visualizaImagem'和'deletaImagem'可以正常工作。

<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. JS:当我单击上载按钮(不是此代码的一部分)时,图像数据将通过“数据:dados”传递,在特定控制器中由“ salvaImagem”读取,然后附加到页面中。 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. 该图像实际上是附加的,但是没有CSS样式,也没有对应该绑定到上述相同类的函数的响应。

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;
}

Since I assume you are binding events (click etc... ) on document.ready, any new items added later will not have those events. 由于我假设您正在document.ready上绑定事件(单击等),因此以后添加的任何新项目都不会包含这些事件。

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... 至于样式,除非您使用jQuery动画等,否则它不会发生。

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). 如果您收到以html格式的ajax响应,则必须在输入html(从ajax接收到)中编写相对于root元素的javascript代码。

1. 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)) ; 并且您应该像这样附加html: $('#imagens').append($(img)) ;

3. 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. 将元素附加到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 comes at the end/during javascript, javascript coming way after CSS. 我的解决方案和理解是AJAX在javascript末尾出现,而javascript在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. 我最终使用需要将元素作为参数的函数来设置需要在javascript中最动态的样式。 works like a charm! 奇迹般有效!

function styleElement(elem){
    elem.style.visibility = "hidden";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM