0

I have the following code to return a Chinese word's English translation on hover.

//return Chinese/English words from database
$("#npc_dialog span").on("mouseover", function() {
    var word = $(this).text();
    $("#currentWord").text(parseHoveredText(word));
}).on("mouseout", function() {
    $("#currentWord").empty();
});

It works with a for loop:

function parseHoveredText (word) {
    for (vocab in hoveredWords) {
        if(word.toLowerCase() === vocab) {
            return hoveredWords[vocab];
        }
    }
};

But does not if I use jQuery $.each.

function parseHoveredText (word) {
    $.each(hoveredWords, function(key, value) {
        if(word.toLowerCase() === key) {
            return value;
        }
    });
};

In both cases, the console.log() of the returned value yields the same value. Why doesn't the jQuery work?

In the for loop:

console.log(hoveredWords[vocab]); gives: You

In the jQuery $.each:

console.log(value); gives: You

2 Answers 2

3

it is because you have a anonymous function, when you return the value it is from the each callback function not from the parseHoveredText method.

function parseHoveredText (word) {
    var val;
    $.each(hoveredWords, function(key, value) {
        if(word.toLowerCase() === key) {
            val =value;
            //return false to prevent any further iterations
            return false;
        }
    });
    return val;
};

but from the looks of it, it should be as simple as

function parseHoveredText (word) {
    return hoveredWords[word.toLowerCase()];
};
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome. The simplified function works perfectly. How is it that return hoveredWords[word.toLowerCase()]; is able to find the word I'm looking for? Is the loop assumed?
hoveredWords is a object which contains key value pairs.... so you can use member operators to fetch the value
1

The return statement in each will end the each loop instead of returning value from function. You need to return false to finish the for loop instead of returning the value. You should assign value to some variable (that is accessible out the each block) in each loop before returning from each function and return that value from function parseHoveredText

function parseHoveredText (word) {
    var result = "";
    $.each(hoveredWords, function(key, value) {
        if(word.toLowerCase() === key) {
            result = value;
            return false;
        }
    });
    return result;
};

1 Comment

You need to return false to make the loop stop.

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.