drfu80954 2015-12-01 18:17
浏览 70
已采纳

jQuery函数优于ajax

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

$(".divexpand").mouseenter(function(){
var alto = $(this).find('.checkalign').length*21+"px";
$(this).animate({height: alto}, 100)
$(this).css("z-index","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?

Thanks

  • 写回答

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

    $("body").on('mouseenter','.divexpand',function(){
        var alto = $(this).find('.checkalign').length*21+"px";
        $(this).animate({height: alto}, 100)
        $(this).css("z-index","100")
    });
    

    Edit:

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵