简体   繁体   中英

Strange behavior of $.each in jQuery

I'm writing a piece of code that gets SVG paths from a MySQL database and draws the shapes using raphaeljs.com's script. I'm having trouble with the onmouseover property: I want each shape to get a different fill-color when I hover them, but what happens is that whenever I hover any of the shape, the last shape drawn is colored and not the one I'm hovering.

Here's the code of the JS function that draws the shapes contained in data:

function drawShapes(data,geolevel,transparent){
    $.each(data, function(code,shape){
        var contour = shape.contour.split(" ");
        attributes = {};
        attributes["fill"] = (transparent ? "none" : shape.fillcolor);
        attributes["fill-opacity"] = "0.75";
        attributes["stroke"] = shapeProperties[geolevel]["stroke"];
        attributes["stroke-width"] = shapeProperties[geolevel]["stroke-width"];

        index = shapeProperties[geolevel]["prefix"] + code;
        shapes[index] = drawPath("M " + contour.join(" ") + " z").attr(attributes);
        shapes[index].fill = shape.fillcolor;
        if (!transparent) {
            shapes[index][0].onmouseover = function () {
                shapes[index].attr({fill: hoverfill});
            };
            shapes[index][0].onmouseout = function () {
                shapes[index].attr({fill: shapes[index].fill});
            };
        }
    });
}

shapeProperties is a global variable (object) containing properties of the shapes depending on their type.

Is there something wrong around my onmouseover? For information my script is loosely based on this demo: http://raphaeljs.com/australia.html

Thanks in advance!

This line:

index = shapeProperties[geolevel]["prefix"] + code;

looks like it's declaring a global variable, which may be the cause of your problem. Use the var keyword so that it's scoped to the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM