简体   繁体   English

jQuery-是否需要在另一个函数中使用第一个函数的变量?

[英]jQuery - Need to use variable from first function inside another function?

Uber Noob but I thought I was close. 优步Noob,但我以为我很亲密。

var markers = $j('span.marker');

$j(markers).each(function () { //function to store original marker positions 
    var startOrigin = $j(this).css('margin-left');

});

$j("a.timeline-view").click(function () { //function to return markers to stored positions
    $j(markers).each(function () {

        $j(this).animate({
            marginLeft: startOrigin
        })

    });
});

Second function can't find the var?? 第二个函数找不到var ??

I assume that $j == alias to jquery 我假设$ j == jquery的别名

The solution to your problem is using the jquery .data('name', val) to store the value bound to an element and then retrieve it with .data('name') when necessary. 解决问题的方法是使用jquery .data('name', val)存储绑定到元素的值,然后在必要时使用.data('name')检索它。

$j(markers).each(function(){ //function to store original marker positions 

       $j(this).data('startOrigin', $j(this).css('margin-left'));

});

$j("a.timeline-view").click( function() { //function to return markers to stored positions
    $j(markers).each(function(){
        var marker = $j(this);
        marker.animate({marginLeft : marker.data('startOrigin') })
    });         
});

check http://api.jquery.com/jQuery.data/ for more info on using jQuery data 检查http://api.jquery.com/jQuery.data/了解有关使用jQuery数据的更多信息

To explain why your code doesn't work... 为了解释为什么您的代码不起作用...

A function in Javascript has in scope all variables that were declared in containing functions or in that function. Javascript中的函数的作用域是在包含函数或该函数中声明的所有变量。 Using the var keyword sets a variable to the current scope. 使用var关键字将变量设置为当前作用域。 In your example, startOrigin is only in the scope of the first function. 在您的示例中, startOrigin仅在第一个函数的范围内。 If you put it in the parent scope, all the functions in your example will have it in their scope: 如果将它放在父作用域中,则示例中的所有函数都将在其作用域中包含它:

var markers = $j('span.marker');
var startOrigin;  // declare the variable in this scope

markers.each(function () { //function to store original marker positions 
    startOrigin = $j(this).css('margin-left'); // use the parent scope
});

$j("a.timeline-view").click(function () { //function to return markers to stored positions
    markers.each(function () {

        $j(this).animate({
            marginLeft: startOrigin // use parent scope
        })

    });
});

Note, however, that this example is kind of broken anyway. 但是请注意,无论如何,这个示例还是很糟糕的。 You are looping through the whole set of markers, overwriting the startOrigin each time. 您循环遍历整个标记集,每次都覆盖startOrigin You need to use data as Tom Tu said in his answer to set data for an individual DOM element. 您需要使用data汤姆涂在说他的回答为一个单独的DOM元素集数据。

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

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