Help understanding jQuery button enable/disable code

后端 未结 7 913
孤独总比滥情好
孤独总比滥情好 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 20:01

    These lines are in the middle of a method that takes two parameters.

    n // whether to show the next button
    p // whether to show the previous button
    

    Either of these buttons can be null or undefined, which causes jCarousel to look at other factors, like whether or not the carousel is locked.

    Take a look at this:

      lock: function() {
          this.locked = true;
          this.buttons();
      },
      unlock: function() {
          this.locked = false;
          this.buttons();
      }
    

    If you look a few lines up from your two lines, you'll see that this.locked is taken into consideration for setting n and p when they are not passed in as true.

    Let's break apart one of the lines a bit:

    this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
    
    bindMethod = n ? "bind" : "unbind"; // bind if n is true; otherwise unbind
    this.options.buttonNextEvent // defaults to "click", can be changed in the options
    this.funcNext // function() { self.next(); }; // self is a local available to the closure
    
    changeClass = n ? "removeClass" : "addClass" // same as above
    this.className("jcarousel-next-disabled") // adds -vertical or -horizontal to the class
    
    toDisable = !n // Effectively
    

    So, one way this might work would be:

    this.buttonNext.bind("click", function() { self.next(); }).removeClass("jcarousel-next-disabled-horizontal").attr("disabled", false);
    

    And as other pointed out, JavaScript supports both bracket and symbol notation. The following two are identical:

    x.y
    x["y"]
    

    Note that bracket notation is a bit more flexible:

    x.omg-omg // Illegal
    x["omg-omg"] // Legal
    

    Also note that methods are just property lookup plus invocation. The following two are identical:

    x.omg()
    x["omg"]()
    

    Which means you can also do this:

    x[someVariable]()
    

    Tada! Hope that helped.

提交回复
热议问题