简体   繁体   中英

How to maintain jquery after ajax change the html?

Basically I got some jquery like this:

$(".dates").on("mouseover", function(){
        $(this).css("background-color","red");
    });
    $(".dates").on("mouseout", function(){
        $(this).css("background-color", "white");
    });

and below this code I got an ajax request that change the content of its parent element:

$.ajax({
        url : "includes/calendar.php",
        type : "POST",
        data : {
            "count" : count
        },
        success : function(data){
            $('#calendar').html(data);
    }

the class .dates are elements in the span with id #calendar and the data that ajax received is another set of dates with class .dates

but after the ajax request completes and changes the html in #calendar , the jquery on dates no long works.

is there any way to maintain the jquery on the .dates elements after ajax request without copying the jquery code inside of ajax success?

You need to use event delegation since you are dealing with dynamic elements

$('#calendar').on("mouseover", ".dates", function () {
    $(this).css("background-color", "red");
}).on("mouseout", ".dates", function () {
    $(this).css("background-color", "white");
});

You need to use event delegation as you are using dynamic elements

Change your code as

$("#calendar").on("mouseover",".dates", function(){
    $(this).css("background-color","red");
});
$("#calendar").on("mouseout", ".dates",function(){
    $(this).css("background-color", "white");
});

For more details and possibilities, read about the .on(events [, selector ] [, data ], handler(eventObject)) method in the jQuery documentation :

$(document).on("mouseover",".dates", function(){
    $(this).css("background-color","red");
});
$(document).on("mouseout",".dates",  function(){
    $(this).css("background-color", "white");
});

Use on

$(document).on("mouseover",".dates", function(){
    $(this).css("background-color","red");
});
$(document).on("mouseout",".dates",  function(){
    $(this).css("background-color", "white");
});

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