简体   繁体   中英

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. The user clicks the button and the array is passed into Function B... All I have is Function 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/

When creating the button in Function A, could you not do the following:

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。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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