我有一个相当大的 html 页面,我注意到我的点击显示/隐藏过程显得有点迟缓。
我还发现,如果我使用“mouseenter”代替“click”,响应几乎是瞬时的(而不是使用“click”时的 2 秒)。
$("button.showhide").click(function() { $("#"+$(this).attr("id")+"-1").toggle() });
versus
$("button.showhide").mouseenter(function() { $("#"+$(this).attr("id")+"-1").toggle() });
有没有办法让click事件和mouseenter事件一样快?
谢谢。
编辑: 以下内容有助于解释这种行为吗? (没有提到 mouseenter 的“javascript 事件”。)
.click() 将事件处理程序绑定(bind)到“单击”JavaScript 事件,或在元素上触发该事件。
.mousedown() 将事件处理程序绑定(bind)到“mousedown”JavaScript 事件,或在元素上触发该事件。
.mouseenter() 绑定(bind)一个事件处理程序,当鼠标进入某个元素时触发该事件处理程序,或在某个元素上触发该处理程序。
最佳答案
您应该使用委托(delegate)来触发事件(从 jQuery 1.7 开始,使用 on
方法进行事件绑定(bind)):
$("button").on('click','.showhide',function(){/*...*/});
您可以提高事件处理的速度,但这取决于 html 标记。
例如,如果所有 showhide
按钮都分组在某个 div 中,而其他一些按钮则分散在整个主体中,那么您应该使用如下所示的内容:
$("button-container-selector").on('click','button.showhide',function(){/*...*/});
关于javascript - Jquery .mouseenter() 事件比 .click() 或 .mousedown() 事件快得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9279792/