Brad
Brad

Reputation: 417

Passing variable to child function javascript

I've looked at multiple questions in search for an answer however to no avail, I'm trying to obtain the variable from a parent function and passing it like "a(b)" doesn't seem to work I cannot for the life of me obtain 'item_classes', is there another way in which I can write my code in order for it to be operable

$(document).ready(function () {
    $('.nm-more').hover(function () {
        var item_num = $(this).data('stg-id');
        var item_names = $(this).data('stg-items');
        var item_classes = $(this).data('stg-class');
            item_names.forEach(function (entry) {
            var item_index = item_classes[entry];
            alert(entry + ' ' + item_index);
        });});

    });
});

Here is a jsfiddle http://jsfiddle.net/bgzkge65/25/

Upvotes: 0

Views: 121

Answers (1)

Mouser
Mouser

Reputation: 13304

Problem solved:

http://jsfiddle.net/bgzkge65/27/

$(document).ready(function () {
    $('.nm-more').click(function () {
        var item_num = $(this).data('stg-id');
        var item_names = $(this).data('stg-items');
        var item_classes = ($(this).data('stg-class'));

        item_names.forEach(function (entry) {

            var item_index = item_classes[item_names.indexOf(entry)];
            alert(entry + ' ' + item_index);
        });

    });
});

And HTML changes:

            <li class="nm-more" data-stg-id="2" data-stg-items='["Mark as read", "Mark as unread", "Flag all items", "Unflag all items"]' data-stg-class='["readit", "unreadit", "flagit", "unflagit"]'>Mark all</li>
            <li class="nm-more" data-stg-id="1" data-stg-items='["Mark as read", "Mark as unread", "Flag items", "Unflag items"]' data-stg-class='["readit", "unreadit", "flagit", "unflagit"]'>Selected</li>

What I did:

First of all: data-stg-class wasn't formatted as an array. I reformatted and made it an array.

The code was actually correct, but you are using named keys, but you need to use indexes here. So entry should be an index and not a reference to a named key from data-stg-class. So I used item_names.indexOf(entry) to retrieve the proper index and return the correct value.


Instead of array.indexOf, you could also retrieve the index from forEach. It's the second argument of that function, either declare it in the function declaration or retrieve it with arguments[1]. In this case the indexes of both arrays match which makes this alternative solution viable.

Upvotes: 1

Related Questions