简体   繁体   中英

Translate this jquery into coffee script?

I'm unsure how to structure the following. This works fine:

  $('.hover li').on 'hover', (ev) ->
    $(this).addClass('active')

I know I can use 'toggle' instead of 'addClass', but for other reasons I need a handler out function passed. So I tried this:

  $('.element').on 'hover', (ev)
    -> $(this).addClass('active'),
    -> $(this).removeClass('active')

This returns an error - 'unexpected ,'. I've tried other variations, and most of the examples I've found online do not use the .on 'hover' (ev) -> format.

You cannot use on() for this if you'd like to attach both event handlers at a time.

You need to use hover() :

$('.element').hover(
  (ev) -> $(this).addClass 'active'
  (ev) -> $(this).removeClass 'active'
)

or even better, utilizing toggleClass()

$('.element').hover (ev) -> $(this).toggleClass 'active'

jQuery's toggle function takes two functions, which I think is what you're after:

$('.element').toggle 'hover', 
    (ev) -> 
        $(this).addClass('active')
        # Do other stuff...
    (ev) -> 
        $(this).removeClass('active')
        # Do other stuff...
$('.element').on 'hover', (ev) ->
  $(this).addClass('active').removeClass('active')

should do it. Although I don't get it. Your adding the class active and then removing it. Nevertheless, the above code is valid coffeescript at least.

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