开发者

How can I reference a JavaScript object if I have the name in a variable?

I have several objects on a page... I know the name of one of the objects and it's stored in a variable called editorId.开发者_如何学Go How can I access that object's methods? editorId.someFunction() doesn't work because the value of the variable is the object's name.


If it's a global variable you could just do var editor = window[editorID];.

If it's local you could do var editor = (new Function('return ' + editorID))();.

Then you could do editor.blah();


If you are referring to an HTML element on the page, you can use:

document.getElementById(editorId);

If you are referring to the name of a JavaScript object, you can try eval(), which is not very efficient:

var obj = eval(editorId);
// obj.someFunction()


use document.getElementsByName(editorId). Alternatively if your name is actually an ID, use getElementById()

http://www.w3schools.com/jsref/met_doc_getelementsbyname.asp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜