简体   繁体   中英

CoffeeScript: toggle “true” and “false” of an attribute

I know that this should be pretty easy, but after searching around, I just don't seem to be able to find an answer.

I want to toggle the value of an aria attribute between true and false . I hoped there is some easy way for doing this, but I could only come up with the following:

  if @container.attr('aria-hidden') == 'true'
    @container.attr('aria-hidden', 'false')
  else
    @container.attr('aria-hidden', 'true')

I tried stuff with negating the values, but didn't succeed (I guess there's a problem between string booleans and real booleans, I mean false and "false" ).

I hoped that jQuery would offer something like this:

@container.toggleBool('aria-hidden')

There is no toggleBoolean method. All you can do is:

@container.attr 'aria-hidden', !/^true$/.test(@container.attr('aria-hidden'))

PS: And I still think that your snippet is more readable, so preferred.

Starting with jQuery 1.1, .attr() accepts a function as second argument, whose parameters are the index position of the element in the set, and the old attribute value. So, what about something like that (untested):

toggleBool = (index, attr) -> if attr='true' then 'false' else 'true'

[...]

 @container.attr('aria-hidden', toggleBool)

If you find yourself doing this a lot, you could create a simple function to flip the strings 'truth value', assuming the string is always either 'true' or 'false':

flip = (x)->{'true':'false', 'false':'true'}[x]
. . .
@container.attr 'aria-hidden', flip(@container.attr('aria-hidden'))

but if it's neither, then it will return undefined, which may or may not be what you want:

coffee> flip('true')
'false'
coffee> flip('false')
'true'
coffee> flip('abcd')
undefined

I came up with this solution. At least it saves a few keystrokes.

handleEnterAndSpace: ->
  @container.attr('aria-hidden', !@isOpen())

isOpen: ->
  @container.attr('aria-hidden') == 'true'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM