代码之家  ›  专栏  ›  技术社区  ›  Joe Bobby

无法让JSFiddle上班

  •  -2
  • Joe Bobby  · 技术社区  · 13 年前

    我将下面的代码添加到我的 JSFiddle 它停止工作了,我认为这是一个简单的解决方案,但我无法解决:

    $('html, body').animate({
        scrollTop: target.offset().top
    }, 200);
    
    // assign the correct target
    var target = $('#if_two');
    
    // scroll!
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 200, function(){
        target.css({'border-color': 'red'})
    });
    

    我做错了什么?

    3 回复  |  直到 13 年前
        1
  •  2
  •   tleef    13 年前

    问题只是代码的排序问题。当代码被评估时,它实际上更像这样工作

    var target;
    
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 200);
    
    // assign the correct target
    target = $('#if_two');
    
    // scroll!
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 200, function(){
        target.css({'border-color': 'red'})
    });
    

    这个过程被称为可变吊装。所以什么时候

    $('html, body').animate({
        scrollTop: target.offset().top
    }, 200);
    

    执行, target 仍然未定义。如果您按照以下方式对代码进行排序,它就会起作用。

    // assign the correct target
    var target = $('#if_two');
    
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 200);
    
    // scroll!
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 200, function(){
        target.css({'border-color': 'red'})
    });
    

    小提琴在这里: http://jsfiddle.net/TomLee/TwtD9/5/

        2
  •  0
  •   Simon    13 年前

    在定义目标之前,您正在使用它。工作示例请参见此处: http://jsfiddle.net/TwtD9/4/

    // assign the correct target
    var target = $('#if_two');
    
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 200);
    
    // scroll!
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 200, function(){
        target.css({'border-color': 'red'})
    });
    
        3
  •  0
  •   mindandmedia    13 年前

    所有的评论和答案当然都是对的,但你知道开发者控制台(大多数浏览器中的f12)吗?因为如果你打开控制台,你会看到错误,如上所述:

    'Uncaught TypeError: Cannot call method 'offset' of undefined'
    
    推荐文章