drfu80954 2015-12-01 18:17
浏览 70


I have some jQuery functions defined over some mouse events, for example something like

var alto = $(this).find('.checkalign').length*21+"px";
$(this).animate({height: alto}, 100)

This works well in all my .divexpand classes, the problem is when i have some of my content generated with ajax, something like

ajax.open("GET", "modules/activityedit-prop.php?id="+id);
ajax.onreadystatechange=function() {
if (ajax.readyState==4) {
  divContenido.innerHTML = ajax.responseText

In that case, .divexpand classes in activityedit-prop.php are ignoring the jQuery functions...

Can someone tell me why?


  • 写回答

2条回答 默认 最新

  • douyu3145 2015-12-01 18:26

    This is because when you run $(".divexpand").mouseenter() it binds a mouseenter event to each divexpand that exists on the DOM at that time. So by the time your AJAX is ran, the binding has already happened.

    What you need to do is bind the mouseenter event to an element that encompasses all .divexpand (such as the body) and tell it to trigger only on child elements that fit a certain selector. more about jQuery.on

        var alto = $(this).find('.checkalign').length*21+"px";
        $(this).animate({height: alto}, 100)


    After reading Hackerman's comment on Zakaria Acharki's answer I looked up if there was really anything wrong with using document as the delegate. I found this answer on a separate question that explains that you shouldn't use document to delegate events and it's best practice to use the closest parent to the element. I updated my code to use body instead of document (since i don't know what the closest parent element in this case is).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 商城生产日期批次库存问题
  • ¥15 esp8266控制共阳极wrgb灯板无法关闭所有led灯
  • ¥100 python读取速度问题
  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle