SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist bradical1379's Avatar
    Join Date
    Feb 2007
    Posts
    442
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Global variable not valid in callback function?

    I am using jQuery 1.4.2 and I am trying to carry over the global variable totaltabs into my JSON callback function. The code seems to work properly, however, in my loadJSON function after the callback function loads the data, my totaltabs variable will not increment.

    Here is a peak at my code. Any ideas?

    totalItems is loaded from another function, not relevant to my example.

    Code JavaScript:
    var totaltabs = 0;
     
    $(document).ready(function(){
     
    	resize();
     
     
    	for(i = 0; i < totalItems.length; i++){
    		loadJSON(totalItems[i]);
    	}
     
    });
     
    function loadJSON(params) {
     
    	$.getJSON("/path/to/json",function(data){
     
    		totaltabs++;
     
    		alert(totaltabs);
     
    		if (data.TotalItems == 0) {
    			$("#tab-"+totaltabs+" ul").append('<li><div class="wrap"><p>No items found.</p></div></li>');
    		}
    		else {
    			$.each(data.Item, function(i,item){
     
    				var title = item.Title;
     
    				if (null != title)
    				{
    					$("#tab-"+totaltabs+" ul").append('<li><div class="wrap"><div class="desc">' + title + '</div></div></li>');
    				}
    			});
    		}
     
     
    		$("#tab-"+totaltabs+" .title a").attr("href", data.ItemURL);
    		$("#tab-"+totaltabs+" .title a").append(" (" + data.TotalItems + ")");
     
    	});
     
    }

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    3 Thread(s)
    Try using a globally accessible global variable.

    Code javascript:
    var window.MYPROJECTNAME.totaltabs = 0;
    ...
    $.getJSON("/path/to/json",function(data){
        window.MYPROJECTNAME.totaltabs++;
        // it's okay to assign totaltabs locally now, as it's not being updated from here on in.
        var totaltabs = window.MYPROJECTNAME.totaltabs;
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •