-1
$(document).ready(function() {  

    var totalTitles = "";

    function getSubtitles() {
        for(var i=0; i<currentArray.length; i+=2) {
            totalTitles += "<li><a href='" + currentArray[i+1] + "'>" + currentArray[i] + "</a></li>";
        }

        alert(totalTitles);
    }

    $("#menu-header .mainTitles").click(function() {
        getSubtitles();
    });

    alert(totalTitles);
});

I can load the totalTitles variable in a for loop. However, when the for loop is finished, the totalTitles variable has the default value of " ".

nem035
  • 34,790
  • 6
  • 87
  • 99
Ahmet
  • 314
  • 5
  • 15
  • please take look at this link : http://stackoverflow.com/questions/3352020/what-is-the-best-way-to-set-a-global-variable-in-javascript – Nima Derakhshanjan Oct 27 '14 at 17:36
  • What is the length of `currentArray`? It's probably 0... – nem035 Oct 27 '14 at 17:36
  • currentArray isn't important. This is part of my code. I mean you can delete currentArray. My problem how do i set the global veriable in function ? – Ahmet Oct 27 '14 at 17:38

2 Answers2

0

try this :

    window.totalTitles = "";

    $(document).ready(function() {  

        function getSubtitles() {
            for(var i=0; i<currentArray.length; i+=2) {
                window.totalTitles += "<li><a href='" + currentArray[i+1] + "'>" + currentArray[i] + "</a></li>";
            }

            alert(window.totalTitles);
        }

        $("#menu-header .mainTitles").click(function() {
            getSubtitles();
        });

        alert(window.totalTitles);
    });
Nima Derakhshanjan
  • 1,380
  • 9
  • 24
  • 37
  • $("#menu-header .mainTitles").click(function() { getSubtitles(); }); If i use it like this totalTitles happens default when the click function over. But i use the funciton without $("#menu-header .mainTitles").click() totalTitles doesnt happen default value. – Ahmet Oct 27 '14 at 17:54
0

$(document).ready(function() {

    var x = "";

    $("#anyElement").click(function() {
        x = "test";
        alert(x);
    });

    alert(x);
});

When firs alert works, messagebox shows "test". when second alert works, messagebox shows " ".

    $("#anyElement").click(function() {
        // How can i set the x veriable as "test" here
    });
Ahmet
  • 314
  • 5
  • 15