简体   繁体   中英

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM