I have two elements and will get strings inside. (and i use .each` function)
The problem is that the second array (after got string by .each), is replace the first one.
Sorry, if you don’t understand, but try to look below…
$('div').each(function () {
var data = [];
$('li', this).each(function () {
data.push($(this).text());
});
var data_length = data.length;
$(this).children("code").html(data + "");
$("code").click(function () {
data.move(data_length - 1, 0);
$(this).html(data + "");
});
});
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
Demo: http://jsfiddle.net/kdpN7/
What did I do wrong?
For the same reason you do
$(this).children('code')you should also bind your click event with a scope.The problem is, you’re iterating over 2 divs (your
each) which means you’re binding$('code')twice. The first timecodeis bound to click, it binds with the first data array (the 1’s) and then it is bound a second time with (the 2’s). So it IS first doing your click code for the 1s and then immediately running it for the 2s, thus overwriting. Change to$(this).find("code")(orchildren) and it works as expected.http://jsfiddle.net/kdpN7/1/