1

This works ok:

$('#icon1').live("hover", show_popup, hide_popup);
$('#icon2').live("hover", show_popup, hide_popup);
$('#icon3').live("hover", show_popup, hide_popup);

But this does not works and has no error:

var icons = ['#icon1', '#icon2', '#icon3'];
for (icon in icons)
    $(icon).live("hover", show_popup, hide_popup);

What is wrong with that code?

3 Answers 3

2

The for in loop works as:

for(var key in obj)

In an array, the keys are numeric indices, i.e. 0, 1, 2, etc. The corresponding value each time is obj[key] (with obj being a normal object or an array).

You should use a for(var i = 0; i < arr.length; i++) loop for arrays, but apart from that, this should work as well:

$("#icon1, #icon2, #icon3").live(...);

Or, if you want to match all #iconXXX elements:

$("[id^='icon']").live(...);

Note that if you're using jQuery 1.7 you can use .on, which is a normalized function for .bind/.live and should work neater.

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

Comments

2

You should use the following code:

var icons = ['#icon1', '#icon2', '#icon3'];
for (var icon in icons) {
    $(icons[icon]).live("hover", show_popup, hide_popup);
}

Because in a for-in statement like for (var prop in obj), prop here is actually a index or property name of the obj object. And if you want to refer to the property of a object, use [] expression.

By the way, when use a for-in loop, you would better do it as:

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        // do something with obj[prop]
    }
}

Comments

1

To bind to all the items described in array, you can use Array.join function:

var icons = ['#icon1', '#icon2', '#icon3'];
$(icons.join(",")).live("hover", show_popup, hide_popup);

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.