2013-07-08 39 views
0

我正在使用拉斐爾圖書館製作交互式地圖。作爲UI功能的一部分,我有幾個函數將在mouseover,mouseout和onclick上執行。爲了做到這一點,我必須從Raphael對象中提取出幾個字段。拉斐爾 - 獲取身份證號碼和路徑名稱

我有一個加載頁面加載和使用這個功能來繪製美國和縣地圖JSON文件:

function drawMap(data) { 
    map = Raphael(document.getElementById("us_map_container", 555, 352)); 

    var pathCount = data.length; 

    for (i = 0; i < pathCount; i++) { 
    var currentPath = map.path(data[i][2]); 
    currentPath.name = data[i][0]; 
    currentPath.id = data[i][1]; 
    currentPath.attr({"stroke" : "#FFFFFF", "fill" : "#CBCBCB", "stroke-width" : "0.2"}); 
    currentPath.mouseover(function(e){countyMouseOver(e)}); 
    currentPath.mouseout(function(e){countyMouseOut(e)}); 
    } 
} 

的數據被格式化爲超過3000行與格式

["North Slope, AK", "02185", 
    ["M62", "259L63", "258L64", "257L64", "258L64", "258L64", "258L66", "257L68", "255L70", 
    "256L70", "256L69", "257L69", "258L70", "257L70", "256L71", "256L71", "257L72", "257L72", 
    "258L73", "257L74", "257L75", "257L76", "257L75", "258L75", "258L76", "258L76",   
    "259L77", "259L78", "258L81", "258L82", "259L83", "259L84", "259L84", "259L85", "259L86", "259L87", 
    "259L89", "259L89", "259L90", "258L90", "258L91", "258L92", "258L96", "259L97", "263L97", 
    "265L88", "267L89", "269L87", "270L82", "271L82", "271L72", "272L69", "272L69", "271L68", 
    "271L68", "271L66", "271L64", "271L63", "271L63", "271L62", "271L62", "271L60", "271L60", 
    "271L60", "271L60", "271L59", "271L58", "270L57", "270L57", "271L57", "271L54", "271L54", 
    "272L52", "272L51", "271L50", "270L51", "269L51", "267L52", "267L54", "267L55", "267L56", 
    "265L57", "263L58", "261L59", "261L60", "261L61", "260L62", "259"] 
] 

在這裏,name是縣名和兩個字母的州名縮寫,id是該縣的FIPS編號。這兩個字段分別是索引位置0和1。第三個數組是一組代表縣域邊界的路線。

在mouseover事件中,如何從事件對象中獲取元素的名稱和ID?

到目前爲止,我有

function countyMouseOver(e) { 
    var hover = e.target; 
    var countyName = hover.name; 
    $(hover).attr({"stroke" : "#FF0000", "stroke-width" : "1"}); 
} 

$(hover)讓我設置在鼠標懸停事件線條顏色和厚度,但countyName是空的。

當我在上面的函數中有一個斷點時,我可以得到元素的raphaelid,這與應該是id的FIPS號非常不同。 name字段未定義。

回答

1

我找到了解決方案,並指出將來有人可以使用它。

它歸結爲使用Element.node.setAttribute()的路徑,即

currentPath.node.setAttribute("id", data[i][1]); 
currentPath.node.setAttribute("name", data[i][0]); 

而這些可以通過事件對象通過

e.target.attributes[5].value; //get the name data 
e.target.id; //get the ID of the object 

e.target.getAttribute("id"); 
e.target.getAttribute("name"); 
2

也是另一種解決方案來訪問:

您可以將data("id", id)分配到您的路徑。然後通過this.data("id")檢索它。

編輯

可以兩次分配的數據,它會工作,看DEMO

var paper = Raphael("area", 400, 400); 
var r = paper.rect(100, 100, 70, 40, 5).attr({fill: 'yellow', stroke: 'red'}); 
r.data("id",5); 
r.data("value", 4); 

r.click(function() { 
    alert(this.data("value")); 
    alert(this.data("id")); 
}); 
+0

的鍵值對的值部分可以是一個數組或JSON對象?我嘗試過,並且無法使其工作。 – Jason

+0

我編輯了代碼並添加了一個DEMO – Brian