简体   繁体   中英

How can I get the array outside the function?

$("#div").click(function(){
 $('#myselect').change(function() {
     var names = [];
     $('.checkbox input').each(function() {
           if(this.value != ''){
                 names.push(this.value);
                }
             });
     console.log(names);
  });
});

I need to use the names outside that function to use it on another function. Can anyone tell me how to do it?

$("#dropdown").change(function(){
  console.log(names);
});

names is an array.

Define "names" outside the function...

var names = [];

    $('#myselect').change(function() {

         $('.checkbox input').each(function() {
               if(this.value != ''){
                     names.push(this.value);
                    }
                 });
         console.log(names);
      });

You should call the other function from that change-event handler. Defining the array outside of it would make no sense, it is bound to that event.

function gotNewNames(names) {
    // do something every time the value changes
}

$("#div").click(function(){
    $('#myselect').change(function() {
        var names = [];
        $('.checkbox input').each(function() {
            if(this.value != ''){
                names.push(this.value);
            }
        });
        gotNewNames(names);
    });
});

If you just need to be able to get the current values somewhere else, you should declare the variable in an higher scope, eg in the click handler:

$("#div").click(function(){
    var names;
    $('#myselect').change(function() {
        names = []; // don't forget to reset before filling
        $('.checkbox input').each(function() {
            if(this.value != ''){
                names.push(this.value);
            }
        });
    });
    $("#dropdown").change(function(){
        console.log(names);
    });
});

You mean like this:

Please let me know if I missed anything.

Otherwise hope this helps,

Code

 var names = []; // Move the name array to outer scope 

 $("#div").click(function(){

    $('#myselect').change(function() {

        $('.checkbox input').each(function() {
            if(this.value != ''){
                names.push(this.value);
            }
        });
        console.log(names);
    });

    alert(names);
});

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