且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Jquery 中正确使用 .on 方法

更新时间:2023-02-17 20:00:03

你没有正确使用 .on().如果 #who_me 对象来来去去,这是一个更好的实现.

You aren't using .on() correctly. This is a better implementation if the #who_me object comes and goes.

jQuery(document.body).on('click', '#who_me', function(){
    alert('test123');
    return false;
});

您在 .on() 的 jQuery 对象中使用的选择器必须是在您安装事件处理程序时存在的对象,并且永远不会被删除或重新创建,并且要么是您的对象希望将事件安装在该对象或其父对象上.作为第二个参数传递给 .on() 的选择器是一个可选选择器,它匹配您希望事件发生的对象.如果你想要 .live() 类型的行为,那么你必须在 jQuery 对象中传递一个静态父对象,并在第二个参数中传递一个匹配你想要事件的实际对象的选择器.

The selector you use in the jQuery object for .on() must be an object that is present at the time you install the event handler and never gets removed or recreated and is either the object you want the event installed on or a parent of that object. The selector passed as the 2nd argument to .on() is an optional selector that matches the object you want the event on. If you want .live() type behavior, then you must pass a static parent object in the jQuery object and a selector that matches the actual object you want the event on in the 2nd argument.

理想情况下,您可以在 jQuery 对象中放置一个相对接近动态对象的父对象.我展示了 document.body 只是因为我知道它会起作用并且不知道你的 HTML 的其余部分,但你宁愿把它放在更接近你的实际对象的地方.如果您在 document 对象或 document.body 上放置了太多动态事件处理程序,那么事件处理可能会真正变慢,特别是如果您有复杂的选择器或处理程序频繁点击或鼠标移动等事件.

Ideally, you put a parent object in the jQuery object that is relatively close to the dynamic object. I've shown document.body just because I know that would work and don't know the rest of your HTML, but you'd rather put it closer to your actual object. If you put too many dynamic event handlers on the document object or on document.body, then event handling can really slow down, particularly if you have complicated selectors or handlers for frequent events like click or mousemove.

作为参考,100% 等效于您的 .live() 代码是这样的:

For reference, the 100% equivalent to your .live() code is this:

jQuery(document).on('click', '#who_me', function(){
    alert('test123');
    return false;
});

.live() 只是将其所有事件处理程序安装在文档对象上,并使用事件冒泡来查看页面中其他对象上发生的所有事件.jQuery 已弃用 .live() 因为***不要在文档对象上安装所有实时事件处理程序(出于性能原因).因此,选择一个更接近您的对象的静态父对象.

.live() just installs all its event handlers on the document object, and uses event bubbling to see all the events that happen on other objects in the page. jQuery has deprecated .live() because it's better to NOT install all your live event handlers on the document object (for performance reasons). So, pick a static parent object that is closer to your object.