简体   繁体   English

$ .each在jQuery中的奇怪行为

[英]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. 我正在编写一段代码,该代码从MySQL数据库获取SVG路径,并使用raphaeljs.com的脚本绘制形状。 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. 我在onmouseover属性上遇到麻烦:我希望每个形状在悬停时都获得不同的填充颜色,但是发生的事情是,每当悬停任何形状时,绘制的最后一个形状都是彩色的,而不是我绘制的形状在盘旋。

Here's the code of the JS function that draws the shapes contained in data: 这是绘制数据中包含的形状的JS函数的代码:

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. shapeProperties是一个全局变量(对象),其中包含取决于形状类型的形状属性。

Is there something wrong around my onmouseover? 我的鼠标悬停有什么问题吗? For information my script is loosely based on this demo: http://raphaeljs.com/australia.html 有关信息,我的脚本大致基于此演示: 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. 使用var关键字,以便将其范围限定于该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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