I'm fairly new to JQuery. I've written the following function, I can view the created array in the console so I know that the function works okay. My question is how do use the array outside of the function? I've tried inserting return arr; at the end of the function, but I just can't seem to access the array values!
function css_ts() {
arr = [];
$('.timeslot').each(function(){
var bid = $(this).children("input[type='hidden']").val();
if (bid > 0) {
$(this).css('background-color','blue');
开发者_StackOverflow社区 arr.push(bid);
}
else
{
$(this).css('background-color','#ececec');
}
});
console.log($.unique(arr));
}
arr
insidecss_ts
is implicitly global, because you've omitted thevar
keyword. You should always usevar
when declaring/initializing a variable:var arr = [];
Add the following line to the end of your function:
return arr;
Then use it like this:
var arr = css_ts();
Add a var
before arr = [];
, this makes it local for your function, and you will be able to return it at the end.
Did you declared the arr[] inside the function or outside the function? If you did create it inside the function then no other function can see this variable because of the scope of the variable. Move the declaration outside of the function and give it a try. I hope this helps.
精彩评论