我有这段代码可以按我的意愿工作,但我想把它变成一个函数并在这里和那里重用它。下面是我转换为函数的工作代码。但我做错了什么,因为它不起作用。
在职的
$('div.destination a').click(function(){
    $('html, body').stop(true,false).animate({
        scrollLeft: $( $.attr(this, 'href') ).offset().left 
                        - 1/2 * $(window).width() 
                        + 1/2 * $( $.attr(this, 'href') ).width()
    },
    {
        duration: (Math.abs( $( $.attr(this, 'href') ).offset().left 
                    - $(document).scrollLeft() )) 
                    / 1000 
                    / spaceScaleFactor 
                    / travelRate,
        easing: 'linear',
        queue: false
    });
    $('div.destination').prev().children().children().text(($.attr(this, 'href')).substring(1));
    return false;
});
函数并在单击时调用它(不起作用)
// Make the function and replace 'this' with 'x'
function travelToDestination (x) {
        $('html, body').stop(true,false).animate({
            scrollLeft: $( $.attr(x, 'href') ).offset().left 
                            - 1/2 * $(window).width() 
                            + 1/2 * $( $.attr(x, 'href') ).width()
        },
        {
            duration: (Math.abs( $( $.attr(x, 'href') ).offset().left 
                        - $(document).scrollLeft() )) 
                        / 1000 
                        / spaceScaleFactor 
                        / travelRate,
            easing: 'linear',
            queue: false
        });
        $('div.destination').prev().children().children().text(($.attr(x, 'href')).substring(1));
        return false;
    });
}
//call the function on click using '$(this)' as a parameter
$('div.destination a').click(function(){
    travelToDestination($(this));
}
就像我说的那样,代码可以正常工作。我只是想知道当我尝试使它成为一个函数时我做错了什么。'this' 可能不等于 '$(this)'。谢谢!