如何声明和使用json对象的函数名称? [英] How to declare and use the name of a function from a json object?

查看:367
本文介绍了如何声明和使用json对象的函数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json对象是我在服务器中构建的地理位置集合。每个对象都有两个属性:标记和onClick。

标记用于存储Google Maps标记对象,onClick存储在地图上单击标记时要调用的函数的名称。



当我在客户端使用javascript将位置对象转换为数组时,我创建了标记并将它们分配给数组中的每个位置对象。



我的问题是,当我用onClick属性绑定标记时,该函数将不会在DOM中找到并出错。



有没有办法在json对象中声明一个属性来在事件绑定中使用它?



希望我可以清楚地解释它,如果不是,请让我知道。
$ b $ p

谢谢!

解决方案

在全局对象中,例如

 函数foobar(){alert('foobar')} 

然后您可以通过下标符号获得对它的引用:

  var funcname ='foobar'; 
var func = window [funcname];
func(); //警告

如果该函数是某个其他对象的一部分,只需将该名称用作下标该对象:

  var func = some_obj [funcname]; 


I have a json object collection of geo locations that I build in the server. Each of those objects has two properties: "marker" and "onClick".

Marker is for storing a Google Maps marker object and the onClick stores the name of the function to be called when that marker is clicked on the map.

When I'm pushing the location objects into an array using javascript in the client side, I create the markers and assign them to each location object within the array.

My problem is that when I bind the marker with the onClick property, the function won't be found in the DOM and get an error.

Is there a way to declare a property in a json object for using it on an event binding?

Hope I could explain it clearly, if not, please let me know.

Thanks!

解决方案

If you have a function declared in the global object, e.g.

function foobar() { alert('foobar') }

Then you can get the reference to it via subscript notation:

var funcname = 'foobar';
var func = window[funcname];
func();   // alerts

If the function is part of some other object, just use the name as a subscript on that object:

var func = some_obj[funcname];

这篇关于如何声明和使用json对象的函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆