简体   繁体   中英

jQuery - variable defined inside $.each, but it's undefined outside

I have the following code, which is driving me nuts:

$.each(originalSteps, function() {
                    if($(this).attr('id') == 'ps_attributes_step_'+(parseInt(triggered_step)+1))
                    {
                        alert('testing validity');
                        var newOne = $(this);
                    }
                });
                console.log(newOne)

Now, the alert is being triggered, but newOne is undefined outside the loop. Any Solution to this?

Thanks

That is becuase you have declared the variable inside. Change your code as below.

var newOne;
$.each(originalSteps, function() {
    if($(this).attr('id') == 'ps_attributes_step_'+(parseInt(triggered_step)+1))
    {
        alert('testing validity');
        newOne = $(this);
        return false;
    }
});

console.log(newOne);

Edited to add return false. See comment below for explanation.

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