js访问变量值

时间:2014-01-29 09:49:14

标签: javascript jquery

以下工作正常,但是可以访问'onEnter'中的变量'scrolled'值吗?

$(document).ready(function () {

    var $window = $(window);

    function update() {

        var scrolled = $window.scrollTop();
        return scrolled;
    };



    $('.color').each(function (i, scrolled) {
        var position = $(this).position();

        $(this).scrollspy({
            min: position.top,
            max: position.top + $(this).height(),
            onEnter: function (element, position, scrolled) {
                var scrolled = $window.scrollTop();
                $window.bind('scroll', update);
                console.log(scrolled);
                if (element.id === 'one' || element.id === 'two') {
                    $('.slidingPannel').animate({
                        'background-position-x': '100%'
                    }, 100);
                } else {
                    $('.slidingPannel').animate({
                        'background-position-x': '125%'
                    }, 100);
                }
            },
            onLeave: function (element, position) {
                if (console) console.log('leaving ' + element.id);
            }
        });
    });
});

2 个答案:

答案 0 :(得分:1)

更改为此,您有范围问题:

$(document).ready(function () {
var scrolled;
var $window = $(window);

function update() {
    scrolled = $window.scrollTop();
};



$('.color').each(function (i, scrolled) {
    var position = $(this).position();

    $(this).scrollspy({
        min: position.top,
        max: position.top + $(this).height(),
        onEnter: function (element, position, scrolling) {
            scrolled = $window.scrollTop();
            $window.bind('scroll', update);
            console.log(scrolled); // or should this be "scrolling" ?
            if (element.id === 'one' || element.id === 'two') {
                $('.slidingPannel').animate({
                    'background-position-x': '100%'
                }, 100);
            } else {
                $('.slidingPannel').animate({
                    'background-position-x': '125%'
                }, 100);
            }
        },
        onLeave: function (element, position) {
            if (console) console.log('leaving ' + element.id);
        }
    });
});

});

答案 1 :(得分:0)

我认为你不能将变量名称作为参数名称传递给匿名函数。

这就是你如何接近它。

$(document).ready(function(){

var scrolled;
var $window = $(window);

function update() {
    scrolled = $window.scrollTop();
};



$('.color').each(function (i, scrolledItem) { // edit: changed "scrolled" to "scrolledItem"
    var position = $(this).position();

    $(this).scrollspy({
        // some code here
        onEnter: function (element, position) {
            // scrolled = $window.scrollTop();

             console.log( scrolled ); // hopefull should reference scrolled variable as there is no argument with the same name.

        },
        // some code here
    });
});

});