jQuery中方法链接的缺点和优势是什么? [英] What are downside and advantage of method chaining in jQuery?

查看:93
本文介绍了jQuery中方法链接的缺点和优势是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery中方法链接的缺点和优点是什么?

What are downside and advantage of method chaining in jQuery ?

它比重新声明选择器快吗?

Is it faster than re-declaring selector?

推荐答案

最有可能的优点是

它使您的代码更短,更易于管理.它具有更好的性能(更快). 连锁从左到右开始.因此,最左边的将首先被调用,依此类推.

that It makes your code short and easy to manage.It gives better performance(faster). And the chain starts from left to right. So left most will be called first and so on.

使用链接时,JQuery必须查找一次元素,它将一一执行所有附加的函数.

When chaining is used JQuery has to find the elements once and it will execute all the attached functions one by one.

链接的一个缺点是不必要地过多使用它,这会导致性能下降.

An disadvantage of chaining can be using it unnecessarily too much then it can cause performance degrading.

例如:- 代码1:

​$(document).ready(function(){
    $('#myContent').addClass('hello');
    $('#myContent').css('color', 'blue');
    $('#myContent').fadeOut('fast');
});​

代码2:

$(document).ready(function(){
    $('#myContent').addClass('hello')
          .css('color', 'blue')
          .fadeOut('fast');     
});​

这两个代码都做同样的事情.代码2使用链接,并且代码更快,更短.而且在代码1中,JQuery必须搜索整个DOM来找到该元素,然后在该DOM上执行功能.

Both these code does the same thing. and the Code 2 uses chaining and it is faster and shorter in code. And in Code 1 JQuery has to search the entire DOM to find the element and after that it executes the function on it.

这篇关于jQuery中方法链接的缺点和优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆