简体   繁体   中英

Ajax execute only once inside an event

I have created a widget that displays a html template fetched with an ajax request to the server. I want to refresh the template clicking on a <p> element of the template. However when I click on it, it refreshes the template only once, then, if I try to click again, the event does not respond, it does not execute the request again. This is my code, if someone has any idea what I am doing wrong.

   /******** Our main function ********/
function main() {
    jQuery(document).ready(function ($) {

        var widget_url = "/home/widget?callback=MyCallbackFunction"

        $.ajax({
            url: "/home/widget",
            type: "GET",
            dataType: "jsonp",
            jsonp: "callback",
            success: function (data) {

                $('#example-widget-container').html(data.html);

                $("#panel-sidebar-icon").on("click", function () {

                    $.ajax({
                        url: "/home/widget",
                        type: "GET",
                        dataType: "jsonp",
                        jsonp: "callback",
                        cache: false,
                        success: function (data) {
                            $('#example-widget-container').html(data.html);
                        }
                    });

                });
            }
        });                         


    });
}

The template example:

<aside> 
        <p id="panel-sidebar-icon">Click </p>
        <ul>
                <li>.... </li>              


        </ul>

</aside>

events attached to DOM elements are lost when you replace the container html, so.

change this

$("#panel-sidebar-icon").on("click", function () { 

to this

$("body").on("click", "#panel-sidebar-icon", function () { 

maybe because you create a new DOM object so the event goes with the erasure. You should update simple datas on the element or recreate the same component+event associated to it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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