Reputation: 22167
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?
Upvotes: 0
Views: 128
Reputation: 11820
On this line:
$("code").click(function () { ...
This is telling to update all code
with that information. You need to change it so it's specific to each div:
$(this).find("code").click(function () { ...
Updated fiddle: http://jsfiddle.net/kdpN7/2/
Upvotes: 1
Reputation: 9763
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 time code
is 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")
(or children
) and it works as expected.
Upvotes: 3