jQuery chaining: Can everything be chained? When can we not chain?

人盡茶涼 提交于 2019-11-27 03:21:19

问题


I know that not all jQuery functions can be chained together. Is there a rule of thumb on this. When can we not chain 2 functions together.


回答1:


You can chain when the function returns a "jQuery object".

For example, .css(property, value) can be chained, as the doc says it Returns jQuery:

while .height() cannot, because it returns an integer.

Typically, the functions that returns "jQuery objects" are those which typically would not "return a value", e.g. setter methods (.css(prop, val), .addClass()), event binders (.click(handler)), etc.

(Of course traverse methods (.parent(), .find(), etc.) can also be chained but the returned object will be different from the input.)




回答2:


You can't chain a function that returns something other than a jQuery object. For example, attr() with one parameter to get the value of an attribute.




回答3:


The way to distinguish is that functions which have side effects typically return jquery and can be chained where as functions with an actual return (like .text()) cannot.




回答4:


if in the plugin they do:

return this; //<--jquery object

at the end then u can change it with other plugins :-)



来源:https://stackoverflow.com/questions/5505648/jquery-chaining-can-everything-be-chained-when-can-we-not-chain

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!