无法让 JSFiddle 工作

Cant get JSFiddle to Work

本文关键字:工作 JSFiddle      更新时间:2023-09-26

我将下面的代码添加到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'})
});

我做错了什么?

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

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/

在定义目标之前,您正在使用目标。 有关工作示例,请参见此处: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'})
});

所有的评论者和答案当然都是正确的,但是您知道开发人员控制台(大多数浏览器中的 f12)吗? 因为如果您打开该控制台,您将看到错误,如前所述:

'Uncaught TypeError: Cannot call method 'offset' of undefined'