2016-02-01 56 views
-1
myObject { div: htmlElement, foo1: bar1, foo2: bar2 } 

密钥div原始密钥,它包含此对象的HTML从HTML访问对象?

是否有可能访问/获取/设置myObject和其他价值观:foo1foo2当我有范围htmlElemente.g点击它?

myObject是原型,我不介意制作原型getter/setter,但我不知道如何通过/通过HTML元素访问对象。


使对象:不介意谷歌地图的一部分,它只是一个普通对象..

function customHTML(latlng, foo, map) { 
    this.latlng = latlng; 
    this.foo = foo; 
    this.setMap(map); 
} 
customHTML.prototype = new google.maps.OverlayView(); 

customHTML.prototype.draw = function() { 
    var self = this; 
    var div = this.div; 

    //Create div if there's none 
    if (!div) { 

     div = this.div = document.createElement('div'); 
     div.className = 'custom-html'; 

     var panes = this.getPanes(); 
     panes.overlayImage.appendChild(div); 
    } 

    //Location on map - not relevant for this question 
    var point = this.getProjection().fromLatLngToDivPixel(this.latlng); 
    if (point) { 
     div.style.left = (point.x - 20) + 'px'; 
     div.style.top = (point.y - 64) + 'px'; 
    } 
}; 

//Create new objects 
var data = /*parsed JSON*/; 
var count = data.lenght; 
var myMap = /*Google Map object - not relevant for this question*/; 

for(i=0; i<count; i++) { 
    new CustomHTML(data[i].latlng, data[i].foo, myMap); 
} 

别的地方代码:

//Clicking element that was made above 
jQuery('body').on('click', '.custom-html', function(event) { 

     //I need to access customHTML.foo for example, how? 
     //PS! I need to access it from outside, I cannot 
     //attach this click event in prototype.draw 
} 
+0

'myObject'是JSON吗? – pratikpawar

+0

@pratikwebdev数据是从JSON中获取的,但我构建了自己的原型'myObject',这只是浏览器内存中的一个对象,我需要通过'HTML' *(点击事件是精确的)*在视口中呈现并且是该对象的一部分。 – Solo

+0

@Juhana为什么不呢?字符串格式的HTML元素?进一步渲染这个字符串可以用来渲染元素? – pratikpawar

回答

0

new CustomHTML(data.latlng, data.foo, myMap);赋值给JS变量。

var customEle = new CustomHTML(data.latlng, data.foo, myMap); 

您可以访问它

jQuery('body').on('click', '.custom-html', function(event) { 
    alert(customEle.foo); 
} 

UPDATE要回答你的上的多个元素的第二个问题。

1)在draw函数中分配ID给div

2)在JSON中创建一个结构,将所有customHTML作为id作为关键。

var arrCustomHTML = {}; 
arrCustomHTML.divId = customHTML; 

3)如何检索它。

jQuery('body').on('click', '.custom-html', function(event) { 

     var divId = $(this).prop('id'); 
     var customHTMLForDiv = arrCustomHTML.divId; 
     alert(customHTMLForDiv.foo); 
} 

还有另外一种方法。在创建过程中使用jquery data()函数在创建该元素之后为该div附加customHTML

div.data('customHTML' , customHTML); 

要访问事件:

jQuery('body').on('click', '.custom-html', function(event) { 
     var ele = $(this).data('customHTML'); 
     alert(ele.foo); 
    } 

LMK它是否适合你

+0

这是一个好主意,但如果有多个'CustomHTML'会怎么样?如何访问属于该对象一部分的特定“HTML”元素的正确对象? – Solo

+0

更新了我的答案。 @索罗 – pratikpawar

+0

谢谢,我确定它会工作。我在脑海中使用了'id'或'data-'属性,但我想也许有一种更简单的方法来获取该对象_a.k.a_获取该“HTML”元素的父属性_a.k.a_向上移动在对象的层次结构中使用原型getter和setter。 – Solo