【问题标题】:How can I write this coffeescript so it doesn't refresh my page?我怎样才能写这个coffeescript,这样它就不会刷新我的页面?
【发布时间】:2012-02-25 03:41:34
【问题描述】:

这是我的第一个 Coffeescript 函数,不知道如何在用户点击并触发事件后不刷新我的页面:

jQuery ->
  $(".answer_link").click -> 
    $val = $(this).attr 'id'
    $id = $val.replace(/answer_link_/, '')
    $input = "#new_answer_" + $id
    $($input).toggle 'slow'

谢谢!

【问题讨论】:

    标签: jquery coffeescript


    【解决方案1】:

    我认为这是关于jQueryJavaScript 的问题。 您可以使用.preventDefault() 来执行此操作:

    jQuery ->
      $(".answer_link").click (event)->
    
        #like this
        event.preventDefault()
    
        $val = $(this).attr 'id'
        $id = $val.replace(/answer_link_/, '')
        $input = "#new_answer_" + $id
        $($input).toggle 'slow'
    

    关于preventDefault的更多信息。

    【讨论】:

    • 只是说event 似乎是一个关键字,所以我不会在这种情况下使用它。将event 更改为x 或其他内容。这段代码运行良好,我自己也只是用 cs 编写脚本,但 event 是一个关键字。
    【解决方案2】:

    只需在点击函数的末尾添加一个return false,如下所示:

    jQuery ->
      $(".answer_link").click -> 
        $val = $(this).attr 'id'
        $id = $val.replace(/answer_link_/, '')
        $input = "#new_answer_" + $id
        $($input).toggle 'slow'
        return false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多