Add a JavaScript display to the Home page to count down from 140 characters. (Rails Tutorial, 2nd Ed, Chapter 10, Exercise 7)

前端 未结 7 1087
别跟我提以往
别跟我提以往 2021-02-04 08:32

This exercise was a bit tricky. Figured I\'d post my solution to see if anyone did it differently or if there\'s anyone who knows a better way.

I\'m not sure on best pra

相关标签:
7条回答
  • 2021-02-04 09:39

    Here's my coffeescript version based on Adriano's solution. This ignores whitespace, doesn't involve adding empty divs into the view, and also adds an error class once you get to minus numbers.

    updateCountdown = ->
      text =  jQuery('#micropost_content').val()
      text = text.replace(/\s/g, '');   
      remaining = 140 - text.length
      jQuery('.countdown').text remaining + ' characters remaining'
      jQuery('.countdown').addClass 'alert alert-error' if remaining < 0
      jQuery('.countdown').removeClass 'alert alert-error' if remaining > 0
    
    jQuery(document).ready ->
      jQuery('#new_micropost').append '<span class="countdown">140 characters remaining</span>'
      jQuery('#micropost_content').change updateCountdown
      jQuery('#micropost_content').keyup updateCountdown
      return
    
    0 讨论(0)
提交回复
热议问题