views:

240

answers:

3

I want to access my global javascript variable in JQuery methods. But I am unable to get it when I go to attach a click even to a div. As following.

How can I do that? I mean do I need to rely on hidden fields for some state management?

var divCount = 3;
$(function() {
//divCount is accessible here
    $("#sortable").sortable({
        revert: true
    }); 

    $("#new").click(function(){
        if (divCount<7){
                     //divCount is not accessible here. why? and how?
            var thisCount =  ++divCount;    

            $("#draggable_"+thisCount).addClass("draggable");
        }
    });
});
A: 

This is not make any sense. It is need to be accessible.

Mendy
A: 

use jQuery's data method.

$.data(document.body, 'myglobalvariable', 42);

will set 'myglobalvariable' to value 42. Accessable via

var answerforevertything = $.data(document.body, 'myglobalvariable');

Kind Regards

--Andy

jAndy
+1  A: 

I tried this sample and it worked for me:

var divCount = 3;
$(function() {
    $("#new").click(function(){
        divCount++;
        alert(divCount);
    });
});

So the scope of divCount is not the problem here, but something else is. I suggest you try to pinpoint the cause by commenting out the other jQuery statements until it works, and then remove the comments until the error occurs. Maybe there's a jQuery library file missing (I noticed the jquery-ui tag in your question).

Prutswonder