Javascript Jquery window.load函数和Ajax调用
我在页面中使用以下jquery代码:Javascript Jquery window.load函数和Ajax调用,javascript,jquery,ajax,Javascript,Jquery,Ajax,我在页面中使用以下jquery代码: jQuery(window).load(function(){ jQuery('#narrow-by-list dd > ol.filter_list').each(function(){ var FormHeight = jQuery(this).outerHeight(); if(FormHeight > 70){ jQuery(this).next('.layer_nav_m
jQuery(window).load(function(){
jQuery('#narrow-by-list dd > ol.filter_list').each(function(){
var FormHeight = jQuery(this).outerHeight();
if(FormHeight > 70){
jQuery(this).next('.layer_nav_more').css("display", "inline-block");
jQuery(this).height(70).css("display", "block");
}else{
jQuery(this).height(70).css("display", "block");
}
});
jQuery(".layer_nav_more").click(function(){
jQuery(this).prev('.filter_list').animate({ height:205 }, 500, function() {
jQuery(this).addClass("scrollable");
});
});
});
页面还使用ajax调用来更新其内容,因此在内容刷新后,jquery代码将被忽略。我不知道;我不认为发布处理ajax的完整js文件会对你有所帮助。我想下面几行应该可以让你明白发生了什么:
requestUrl = document.location.href
if (requestUrl.indexOf('#') >= 0) {
var requestUrl = requestUrl.substring(0,requestUrl.indexOf('#'));
}
if (requestUrl.indexOf('?') >= 0) {
requestUrl = requestUrl.replace('?', '?no_cache=true&');
} else {
requestUrl = requestUrl + '?no_cache=true';
}
requestUrl = this.replaceToolbarParams(requestUrl);
this.showLoading();
new Ajax.Request(requestUrl, {
method : 'post',
parameters : parameters,
onSuccess: this.onSuccessSend.bindAsEventListener(this),
onFailure: this.onFailureSend.bindAsEventListener(this)
});
我能做些什么来解决这个问题
编辑: 我根据David的建议修改了代码
jQuery(window).load(function(){
function adjust_list_height(){
jQuery('#narrow-by-list dd > ol.filter_list').each(function(){
var FormHeight = jQuery(this).outerHeight();
if(FormHeight > 70){
jQuery(this).next('.layer_nav_more').css("display", "inline-block");
jQuery(this).height(70).css("display", "block");
}else{
jQuery(this).height(70).css("display", "block");
}
});
}
adjust_list_height();
jQuery(document).on('click', '.layer_nav_more', function(){
jQuery(this).prev('.filter_list').animate({ height:205 }, 500, function() {
jQuery(this).addClass("scrollable");
});
});
});
因此,在刷新内容之后,jquery代码将被忽略
不,不是。很明显,它不会被自动重新调用,但为什么会这样呢?您发布的处理程序用于窗口的加载事件。除非再次加载窗口,否则我不希望代码再次执行
听起来问题在于,在向现有元素添加click
处理程序之后,您正在向页面添加新元素。记住这一点。因此,如果在执行此代码时某个特定元素不存在,它将不会得到单击处理程序
实现这一点的标准方法是将单击事件的处理延迟到父元素。任何公共父元素都可以,只要它在页面的生命周期内没有被删除/替换document
通常用于此,但是任何父级div
或类似的东西也可以使用。大概是这样的:
jQuery(document).on('click', '.layer_nav_more', function(){
//...
});
这样做的目的是将实际的单击处理程序附加到文档
,而不是匹配的.layer\u nav\u more
元素。当任何元素调用单击时,该事件将通过父元素向上传播,并调用它们上的任何单击处理程序。当它到达文档上的这个处理程序时,jQuery将使用第二个选择器过滤原始元素。因此,这将有效地处理来自.layer\u nav\u more
元素的任何单击
当页面内容更改时需要调用的任何其他功能(除可委托事件处理程序之外的功能)都需要在逻辑上需要时重新调用。例如,在一系列元素上执行.each()
,就像您正在做的那样。没有办法“推迟”,因此您希望将其封装在自己的函数中,并在需要重新调用该逻辑时执行该函数。有什么问题吗?@ysrb问题是,在使用ajax重新加载页面内容后,each()函数不再工作。感谢您的解释。请查看问题更新。我应该在onSuccessSend函数中调用adjust_list_height()?它似乎不起作用。我尝试添加jQuery('.layer\u nav\u more').css(“显示”,“内联块”);在onSuccessSend()函数的内部,但它不起作用。我相信这就是我应该添加jquery效果的函数,对吗?