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

前端 未结 4 1355
长发绾君心
长发绾君心 2020-12-10 03:05

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.

4条回答
  •  情歌与酒
    2020-12-10 03:49

    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: enter image description here

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

    enter image description here

    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.)

提交回复
热议问题