user3943604
user3943604

Reputation:

jquery why we get not right values?

$(function () {

    /*
    now we have next lines:
    <div id="cat">
        <a href="#" data-text="category1">category1</a>
        <a href="#" data-text="category2">category2</a>
        <a href="#" data-text="category3">category3</a>
        <a href="#" data-text="category4">category4</a>
    </div>
    */
    var category = $("body").find("#cat a");
    var OdjCategory = {};
    $(category).each(function(category_id,elem) {
        var num = category_id+1;
        $this_category = $(this);
        var timer1 = setTimeout(function(e) {
            $(this).trigger('click');
            var ArrOdjCategory = {
                "CategoryId" : num,
                "Name" : $this_category.attr('data-text')
            };
            OdjCategory[num] = ArrOdjCategory;
            console.log('main array = '+num);
            console.log(OdjCategory);
        }, 1000);
    });     
});

if we use function timeout() timer1, than we get:

{
    1={Object { CategoryId=1, Name="category4"} }
    2={Object { CategoryId=2, Name="category4"} }
    3={Object { CategoryId=3, Name="category4"} }
    4={Object { CategoryId=4, Name="category4"} }
}

but it not right and should been:

{
    1={Object { CategoryId=1, Name="category1"} }
    2={Object { CategoryId=2, Name="category2"} }
    3={Object { CategoryId=3, Name="category3"} }
    4={Object { CategoryId=4, Name="category4"} }
}

Why we get not right values and what we need doing that get right results?

Where error ?

P.S.: if we do not use function timeout() timer1 we get good results... But we need this fucntion for next actions.

Upvotes: 0

Views: 34

Answers (1)

Volune
Volune

Reputation: 4339

$this_category = $(this);

You forgot the var keyword.

In your code, $this_category is considered to be a global variable, so the last iteration of the loop override the previous values, and all the timer functions access to the same value.

Example

Upvotes: 3

Related Questions