[英]how to access object property in javascript
function test(results) {
//Populate the ComboBox with unique values
var Gov;
var values = [];
var features = results.features;
var og;
for (i = 0; i < features.length; i++) {
var aGOV = {
"GovName": features[i].attributes.ENG_NAME,
"GovNO": features[i].attributes.GOV_NO,
"Shape": features[i].geometry
}
og = new Option(features[i].attributes.ENG_NAME, aGOV);
var cbx = document.getElementById("cbxGov");
cbx.options.add(og);
}
}
function gov_selection_change()
{
var cbx = document.getElementById("cbxGov");
var itm = cbx.options[cbx.selectedIndex].value.hasOwnProperty("Shape");
}
html code HTML代码
<select id="cbxGov" onchange="gov_selection_change()">
My problem is im not able to access property of aGOV in my gov_selection_change(
) function, it shows it has no such property, itm is false. 我的问题是我无法在
gov_selection_change(
)函数中访问aGOV的属性,它表明它没有此类属性,它是错误的。
The variable aGOV
is only available in the context of your result()
function. 变量
aGOV
仅在result()
函数的上下文中可用。 If you want to use it from a different function declare it as a global variable. 如果要从其他函数使用它,请将其声明为全局变量。
Example: 例:
var aGOV;
function result()
{
// initialize aGOV
}
function gov_selection_change()
{
// now you can access the aGOV variable
}
The value property of an HTMLOptionElement always returns a DOMString (aka text), not an object. HTMLOptionElement的value属性始终返回DOMString(又名文本),而不是对象。
So you have to save what you want to access in a lookup dictionary and then use the returned value as a lookup key. 因此,您必须将要访问的内容保存在查找字典中,然后将返回值用作查找关键字。
var lookupDictionary = {};
function test(results) {
var lookupKey,
og;
//...
// don´t get the element in the loop
var cbx = document.getElementById("cbxGov");
//...
for (i = 0; i < features.length; i++) {
lookupKey = features[i].attributes.GOV_NO;
lookupDictionary[lookupKey] = {
"GovName": features[i].attributes.ENG_NAME,
"GovNO": features[i].attributes.GOV_NO,
"Shape": features[i].geometry
}
og = new Option(features[i].attributes.ENG_NAME, lookupKey );
cbx.options.add( og );
}
}
function gov_selection_change() {
var cbx = document.getElementById("cbxGov");
var key = cbx.options[cbx.selectedIndex].value;
var itm = lookupDictionary[key].hasOwnProperty("Shape");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.