【问题标题】:Strange behavior of $.each in jQueryjQuery 中 $.each 的奇怪行为
【发布时间】:2012-04-20 08:24:24
【问题描述】:

我正在编写一段从 MySQL 数据库获取 SVG 路径并使用 raphaeljs.com 的脚本绘制形状的代码。我在使用 onmouseover 属性时遇到了问题:我希望每个形状在悬停它们时获得不同的填充颜色,但是发生的情况是,每当我悬停任何形状时,最后绘制的形状都是彩色的,而不是我正在盘旋。

这是绘制数据中包含的形状的 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 是一个全局变量(对象),其中包含形状的属性,具体取决于形状的类型。

我的鼠标悬停有什么问题吗? 有关信息,我的脚本大致基于此演示:http://raphaeljs.com/australia.html

提前致谢!

【问题讨论】:

    标签: javascript jquery onmouseover


    【解决方案1】:

    这一行:

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

    看起来它正在声明一个全局变量,这可能是您的问题的原因。使用 var 关键字,使其作用于函数。

    【讨论】:

      猜你喜欢
      • 2014-12-25
      • 2019-07-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多