Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - Help understanding jQuery button enable/disable code

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 which is JavaScript below

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

It's setting some of the css to set state and either enabling or disabling the button that is in a but I want to modify this once I really understand it. I just can't make out exactly what it's doing 100%.

Trying to understand things such as [n ? 'bind' : 'unbind'] and just the chaining here also. There's a lot going on in those 4 lines.

The code comes from this plug-in: http://sorgalla.com/projects/jcarousel/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first part to understand is symbol resolution. Javacript supports both dot-notation and bracket-notation.

Consider opening a new window.

window.open()

This is dot-notation in action. you're telling the interpreter that "open" can be found on "window". But there's another way to do this

window['open']()

Same thing, but with bracket notation. Instead of using the symbol name directly, we're using a string literal instead. What this means is that by using bracket-notation for symbol resolution, we can do it in a dynamic way, since we can choose or build strings on the fly, which is exactly what this snippet does.

this.buttonNext[n ? 'bind' : 'unbind'](...);

Is analagous to

if ( n )
{
   this.buttonNext.bind(...);
} else {
   this.buttonNext.unbind(...);
}

If you don't recognize the ?: syntax, that's the conditional operator, or conditional expression

[expression] ? [valueIfTrue] : [valueIfFalse]

This is extremely often erroneously called the "ternary operator", when in fact it just a ternary operator (an operator with three operands). The reason for this is because in javascript (and most languages) is the only ternary operator, so that description usually flies.

Does that help? is there anything else you need cleared up?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...