简体   繁体   English

将Javascript转换为Coffeescript

[英]Converting Javascript to Coffeescript

How to change this javascript to coffeescript? 如何将此JavaScript更改为coffeescript?

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
});

I tried this code in my rails project,but it doesn't work 我在我的rails项目中尝试了此代码,但是它不起作用

$(document).on 'page:change', ->
$('a[href^="#"]').click (event) ->
    event.preventDefault()

    target = this.hash
    $target = $(target)

    $('html, body').stop().animate{
        'scrollTop': $target.offset().top
    }, 900,
     'swing', ->
        window.location.hash = target

Do I have something wrong? 我有什么问题吗?

I think this will work: 我认为这会起作用:

$(document).ready ()=>
  $('a[href^="#"]').on 'click', (e)=>
    e.preventDefault()
    target = @hash
    $target = $(target)
    $('html, body').stop().animate scrollTop:$target.offset().top, 900, 'swing', ()=>
      window.location.hash = target

You asked if you've did something wrong, so here's a couple of things to keep in mind (sorry if this is obvious to you already): 您询问您是否做错了什么,因此请记住以下几点(很抱歉,如果这对您已经很明显):

  1. The first line of your CoffeeScript version is completely different than the JavaScript version. CoffeeScript版本的第一行与JavaScript版本完全不同。 ( document.ready vs. document.on('page-change') ) document.readydocument.on('page-change')

  2. CoffeeScript is whitespace-sensitive. CoffeeScript对空格敏感。 I don't know if its just the StackOverflow formatting or in your actual code, but without leading spaces in your second line, the callback passed to $(document).on 'page:change', -> is a no-op. 我不知道它是否只是StackOverflow格式或您的实际代码中,而是在第二行中没有前导空格,则传递给$(document).on 'page:change', ->是无操作的。 In other words, the Javascript version would be $(document).on('page:change', function(){}); 换句话说,JavaScript版本为$(document).on('page:change', function(){});

  3. Similarly, the spaces that indent lines 9 (the one that starts with 'scrollTop' ) and 11 (the one that starts with 'swing' ) are likely to cause problems also. 同样,缩进第9行(以'scrollTop'开头的空间)和第11行(以'swing'开头的空间)的空格也可能引起问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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