0
for (var i = 0; i < 10; i++) {
    array.push($("<a href=\"#\" data-role=\"button\" data-inline=\"true\">" + i + "</a>"));
    $("#row").append(array[i]);
    array[i].click(function () {
        changeval(i);
        console.log(i);
    });
}

My problem is that the function changeval(i) becomes always the same value 10 of i. I try to create buttons with onclick-function in this for-loop. I need a hint.

Jason P
  • 26,984
  • 3
  • 31
  • 45
  • 2
    You need a closure for this, do this way http://jsfiddle.net/HUahz/ `i` is a shared variable in your case and it will have only the last value set by the for loop by the time your handler is invoked. – PSL Oct 11 '13 at 17:51
  • 1
    add `$('[data-role=button]').button();` after appending anchors. updated @PSL demo: http://jsfiddle.net/Palestinian/HUahz/2/ – Omar Oct 12 '13 at 09:58

3 Answers3

3

I would separate the initial adding of the buttons and the 'click' action.

for (var i = 0; i < 10; i++) {
    array
            .push($("<a href=\"#\" data-role=\"button\" data-inline=\"true\">"
                    + i + "</a>"));
    $("#row").append(array[i]);
    array[i].click(function() {
        changeval(i);
        console.log(i);
    });
}

Would be split up to:

for (var i = 0; i < 10; i++) {
    array.push("<a href=\"#\" data-role=\"button\" data-inline=\"true\">"
                    + i + "</a>");
    $("#row").append(array[i]);
};

$('#row').on('click', 'a', function() { 
    changeVal($(this).text());
    console.log($(this).text());
};

Also note that variables and functions within javascript should be written in CamelCaseForBetterReadability. Also note that I got rid of the $() surrounding the array items. Lastly, if you do not want to escape the quotations within your string, you can use a single quotation.

ezis
  • 311
  • 2
  • 10
1

Look into JS closures, the value of i is set to the last iteration of the loop. Wrap that in a self-executing func with i as the param:

for (var i = 0; i < 10; i++) {
    (function(i) {
        array
            .push($("<a href=\"#\" data-role=\"button\" data-inline=\"true\">"
                    + i + "</a>"));
        $("#row").append(array[i]);
        array[i].click(function() {
            changeval(i);
            console.log(i);
        });
    })(i)
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

Use a closure, e.g.

for (var i = 0; i < 10; i++) {
    (function(i) {
        array[i].click(function() { . . . } );
    )(i);
}

If you're using jQuery (seems like it if you're using .click :) you can use

http://api.jquery.com/jQuery.each/

to loop through elements and acheive this same functionality.

Dauh Fhauc
  • 141
  • 11