I’m new to jQuery and trying to understand what is happening in the code below:
var data = {1, 2, 3, 4};
for (var key in data) {
$("#id"+key).click(function() {
$(".class"+key).hide();
});
}
When I run this code, it will hide class4 no matter which id I click. Why is this behaviour the case?
Also, how do I make id1 hide class1, id2 hide class2, and so on?
Working demo
In your for each loop closure is created by handler click, but it points to
keywhich is in global scope. And it is changed. In my code key points to scope created by additional function wrapping.clickandkeyin it points tokeyin scope created by that function, each time it is newvar data = {1, 2, 3, 4};– this is not valid object definition. It should be like this:var data = {key:"value", key2:"value",...};Example above will also work with correctly specified object. Just do not forget that you should also testkeyvariable like this:if(data.hasOwnProperty(key)) {...}in order to filter out.toString,.valueOfetc (default object methods)Or like a workaround – you always can get
keyto build a class name from clicked elementID.
And no closure needed.