[英]How to maintain jquery after ajax change the html?
基本上我有一些这样的jQuery:
$(".dates").on("mouseover", function(){
$(this).css("background-color","red");
});
$(".dates").on("mouseout", function(){
$(this).css("background-color", "white");
});
在此代码下方,我收到了一个ajax请求,该请求更改了其父元素的内容:
$.ajax({
url : "includes/calendar.php",
type : "POST",
data : {
"count" : count
},
success : function(data){
$('#calendar').html(data);
}
.dates类是ID为#calendar
的范围中的元素,而ajax接收到的数据是.dates
类的另一组日期。
但是在ajax请求完成并更改#calendar
的html #calendar
,日期上的jquery不再起作用。
有什么方法可以在ajax请求之后在.dates
元素上维护jquery,而无需在ajax成功内部复制jquery代码?
由于要处理动态元素,因此需要使用事件委托
$('#calendar').on("mouseover", ".dates", function () {
$(this).css("background-color", "red");
}).on("mouseout", ".dates", function () {
$(this).css("background-color", "white");
});
在使用动态元素时,需要使用事件委托
将您的代码更改为
$("#calendar").on("mouseover",".dates", function(){
$(this).css("background-color","red");
});
$("#calendar").on("mouseout", ".dates",function(){
$(this).css("background-color", "white");
});
有关更多详细信息和可能性,请阅读jQuery文档中的.on(events [, selector ] [, data ], handler(eventObject))
方法:
$(document).on("mouseover",".dates", function(){
$(this).css("background-color","red");
});
$(document).on("mouseout",".dates", function(){
$(this).css("background-color", "white");
});
用于
$(document).on("mouseover",".dates", function(){
$(this).css("background-color","red");
});
$(document).on("mouseout",".dates", function(){
$(this).css("background-color", "white");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.