Help understanding jQuery button enable/disable code

后端 未结 7 890
孤独总比滥情好
孤独总比滥情好 2020-12-19 19:21

I grabbed this code form JCarousel and just trying to understand these lines below. I\'m new to jQuery and not that great at JavaScript so I am not sure what is jQuery and

7条回答
  •  一向
    一向 (楼主)
    2020-12-19 19:48

    IMHO, that code is completely unreadable as you would agree.

    As Peter wrote, you need to know that JavaScript method could be called using DOT notation or BRACKET notation.

    Also, jQuery supports chaining.

    Once you know these two things, here's how the code break downs.

    this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
    

    The above line does three things. Binds/Unbinds event, add/removes class and enables/disables the 'buttonNext'.

    1. Bind/unbind step

      this.buttonNext[n ? 'bind' :'unbind']
          (this.options.buttonNextEvent, this.funcNext);
      

      You are calling the 'bind' or 'unbind' depending upon whether n is true or false. More importantly, the bind method call will return this.buttonNext.

    2. addClass/removeClass step

      this.buttonNext[n ? 'removeClass' : 'addClass']
          (this.className('jcarousel-next-disabled'))
      

      Again, based on n, it will either call the addClass or the removeClass method passing it the appropriate class name. You get the same this.buttonNext object back.

    3. Finally, enable/disable button step

      this.buttonNext.attr('disabled', n ? false : true);
      

      Disabling/enabling the button based on whether n is true or false.

    Even though I love chaining, I think chaining was misused in this code.

提交回复
热议问题