0

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?

1
  • Your .move(l - 1, 0) can be written as a.unshift(a.pop()) if I'm not mistaken. Commented Dec 6, 2012 at 15:15

2 Answers 2

3

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.

http://jsfiddle.net/kdpN7/1/

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.