Convert string to variable name in JavaScript

后端 未结 11 1560
无人及你
无人及你 2020-11-22 02:59

I’ve looked for solutions, but couldn’t find any that work.

I have a variable called onlyVideo.

\"onlyVideo\" the string gets passe

11条回答
  •  长情又很酷
    2020-11-22 03:37

    The following code makes it easy to refer to each of your DIVs and other HTML elements in JavaScript. This code should be included just before the tag, so that all of the HTML elements have been seen. It should be followed by your JavaScript code.

    // For each element with an id (example: 'MyDIV') in the body, create a variable
    // for easy reference. An example is below.
    var D=document;
    var id={}; // All ID elements
    var els=document.body.getElementsByTagName('*');
    for (var i = 0; i < els.length; i++)
        {
        thisid = els[i].id;
        if (!thisid)
            continue;
        val=D.getElementById(thisid);
        id[thisid]=val;
        }
    
    // Usage:
    id.MyDIV.innerHTML="hello";
    

提交回复
热议问题