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');
arr.push(bid);
}
else
{
$(this).css('background-color','#ececec');
}
});
console.log($.unique(arr));
}
-
How are you trying to use the returned value? Can you post that piece of code here?Dogbert– Dogbert2011年03月19日 23:30:19 +00:00Commented Mar 19, 2011 at 23:30
-
The code is part of a booking system, the returned values are booking ids. The day is broken down into 15 min segments, the code above finds all the segments that have a booking in them. At the moment each 15 minute segment is a div element with a border, though one or more divs could have the same value, if say a booking lasts an hour. If that is the case I want the four div elements to look joined (ie change the CSS so the borders are removed between the divs). Therefore I would iterate over the returned array to find the bookings that where more than 15 mins and adapt the CSS accordinglyDan– Dan2011年03月19日 23:37:09 +00:00Commented Mar 19, 2011 at 23:37
3 Answers 3
arrinsidecss_tsis implicitly global, because you've omitted thevarkeyword. You should always usevarwhen 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();
Comments
Add a var before arr = [];, this makes it local for your function, and you will be able to return it at the end.
1 Comment
var val = (function() { return test = "3" })(); val === window.test // trueDid 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.