首选使用.on()方法,而不是.click()、. bind()、. hover()、. load()、. ready()等 [英] Preferred use .on() method rather than .click(), .bind(), .hover(), .load(), .ready(), etc
问题描述
我需要一种更好的方法来实现最佳性能,并在可能的情况下使用简洁的代码使用事件委托.
I need a better way to achieve the best performance and concise code use event delegation whenever possible.
尤其是正确的 .ready():
$(document).ready(function()
或
$(document).on('ready',function() //it is correct?
其他?
.click(), .bind(), .hover(), .load(), .ready(), etc.
推荐答案
从jQuery .ready()文档:
jQuery提供了几种附加功能的方法,这些功能将在 DOM准备就绪.以下所有语法均等效:
jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
$( handler )
$( document ).ready( handler )
$( "document" ).ready( handler )
$( "img" ).ready( handler )
$().ready( handler )
从jQuery 3.0开始,仅建议使用第一种语法.另一个 语法仍然有效,但已弃用.
As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated.
所以最好的和最短的方法是这样
So the best and shortest way is this:
$(function() {
// your code
});
对于 .click()
事件及其朋友,情况更为复杂.
.click(function(){})
是.on("click", function(){})
的快捷方式,因此可以互换使用.
For .click()
event and its friends it's more complicated.
.click(function(){})
is a shortcut for .on("click", function(){})
so they can be used interchangeably.
但是 .on()
函数具有用于创建委托事件的附加功能.
However .on()
function has additional feature for creating delegated events.
.on( "click", "selector", function() {});
因此,如果您想要简洁的代码,请坚持使用.on()
版本.
So if you want concise code stick to the .on()
version.
这篇关于首选使用.on()方法,而不是.click()、. bind()、. hover()、. load()、. ready()等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!