简体   繁体   English

在jQuery中将数组从一个函数传递给另一个函数

[英]Pass an array from one function to another in jQuery

I have a page with two functions. 我的页面有两个功能。 Function A compiles an array and displays a button when done. 函数A编译一个数组,完成后显示一个按钮。 The user clicks the button and the array is passed into Function B... All I have is Function A: 用户单击按钮,该数组将传递到函数B中。我所拥有的只是函数A:

function createUploader(){
        var fileArray = new Array();
        var i = 0;
        var running = 0;
        var jList = $( "#list" );
            var uploader = new qq.FileUploader({
                element: document.getElementById('uploadDiv'),
                listElement: document.getElementById('separate-list'),
                action: './includes/ajaxUpload/upload.php',
        sizeLimit: 10485760,
        onSubmit: function(id, fileName){
            running++;  
        },
        onComplete: function(id, fileName, responseJSON){
            fileArray[i] = fileName;
            i++;
            running--;
            if(running==0){
            $('#combineBtn').css("display","");
            $.fancybox.resize();
            $('#fancybox-content').width(290);
            $('#fancybox-wrap').width(310);
            $.fancybox.center
            $('.qq-upload-button').width(290);
            }
        }
            });
        }

Is this even possible? 这有可能吗? What would be the best way to accomplish this? 做到这一点的最佳方法是什么?

Just declare the array outside of the functions, and it can be accessed by them both. 只需在函数外部声明数组,它们就可以被它们两者访问。

var myarray = [];
function foo(val) {
    myarray.push(val);
}

function bar() {
   alert (myarray);
}

Further reading: http://www.digital-web.com/articles/scope_in_javascript/ 进一步阅读: http : //www.digital-web.com/articles/scope_in_javascript/

When creating the button in Function A, could you not do the following: 在功能A中创建按钮时,您不能执行以下操作:

function function_a()
{
    var theArray = [1, 2, 3, 4];
    var theButton = $('<button>Click Me</button>');
    theButton.click(function() { function_b(theArray) });
}

function function_b(myArray)
{
    // Run function code here...
}

您可以将数组序列化为json,将其保存在隐藏字段的value属性中,然后单击按钮时,读取函数B中的隐藏字段值并反序列化JSON。

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

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